CONTENTS OF ‘C’ LANGUAGE



































Introduction to ‘C’
Importance of ‘C’
Sample Program
Basic Structure of ‘C’ Programs
Constants, Variable, Data types
Operators and expressions
Assignment Operators
Decision making and branching
Simple if statement
if .... else statement
Nested if .... else statement
else if ladder
The Switch Statement
The Conditional Operator(?:)
The goto statement
Decision making and looping
The while statement
The do ... while statement
The for statement
Arrays
One -dimensional arrays
Two -dimensional arrays
Multi -dimensional arrays
Handling of character strings
User -Defined Functions
Cal by value
Call by Reference
Recursion
Structures and Unions
Enum
Pointers
Pre-processor
Macro
File Management in ‘C’
Error Handling During I/O Operations

1

Creator of Such a Wonderful language “C”

The C programming language was designed by Dennis Ritchie at Bell Laboratories in
the early 1970s.

Its Immediate ancestors and Influenced by

ALGOL 60 (1960),

CPL (Cambridge, 1963),

BCPL (Martin Richard, 1967),

BCPL Reference Manual by Martin Richards, dated July 1967. The language
described here supplied the basis for much of our own work and that of others. The
linked page discusses the circumstances, while the files linked under it have the
manual itself.

B (Ken Thompson, 1970)

Ken Thompson instead ended up developing a compiler for a new highlevel language he called B, based on the earlier BCPL language developed by
Martin Richard. Where it might take several pages of detailed PDP-7 assembly
code to accomplish a given task, the same functionality could typically be
expressed in a higher level language like B in just a few lines. B was thereafter
used for further development of the Unix system, which made the work much
faster and more convenient.
C was not written as a teaching aid, but as an implementation language. C
is a computer language and a programming tool which has grown popular
because programmers like it! It is a tricky language but a masterful one. Sceptics
have said that it is a language in which everything which can go wrong does go
wrong. True, it does not do much hand holding, but also it does not hold anything
back. If you have come to C in the hope of finding a powerful language for writing
everyday computer programs, then you will not be disappointed. C is ideally
suited to modern computers and modern programming.

Traditionally used for systems programming, though this may be changing in favor of
C++

Traditional C:

2

The C Programming Language, by Brian Kernighan and Dennis Ritchie, 2nd
Edition, Prentice Hall.

Referred to as K&R .

High Levels and Low Levels
Any kind of object that is sufficiently complicated can be thought of as having levels of
detail; the amount of detail we see depends upon how closely we scrutinize it. A computer
falls definitely into the category of complex objects and it can be thought of as working at
many different levels. The terms low level and high level are often used to describe these
onion-layers of complexity in computers. Low level is perhaps the easiest to understand: it
describes a level of detail which is buried down amongst the working parts of the machine:
the low level is the level at which the computer seems most primitive and machine-like. A
higher level describes the same object, but with the detail left out.
C is called a high level, compiler language. The aim of any high level computer language is
to provide an easy and natural way of giving a programme of instructions to a computer (a
computer program). The language of the raw computer is a stream of numbers called
machine code.

Basic ideas about C:
What to do with a compiler. What can go wrong .
Using a compiler language is not the same as using an interpreted language like BASIC or a
GNU shell. It differs in a number of ways. To begin with, a C program has to be created in two
stages:

3

It is not possible to execute this file directly. This development of Unix in C had two important consequences:  Portability. This file is called an object file or executable file. because it eliminated the need to translate the entire operating system to the new assemble language by hand: 4 . It made it much easier to port Unix to newly developed computers.  Secondly. These phases must be executed one after the other. The Compiler A C program is made by running a compiler which takes the typed source program and converts it into an object file that the computer can execute. Compiler languages do not usually contain their own editor. the completed source file is passed to a compiler--a program which generates a new file containing a machine code translation of the source text. This form of the program is called the source program. The executable file is said to have been compiled from the source text. nor do they have words like RUN with which to execute a finished program. Firstly. A compiler usually operates in two or more phases (and each phase may have stages within it). the program is written in the form of a number of text files using a screen editor.

due to its variety of data types and powerful operators. This is. testing and maintenance easier. Several standard functions are available which can be used for developing programs. Many did learn C. o Then use the new compiler to automatically translate the Unix C language source code into the new machine's assembly language. Improvability. thus requiring the User to think of a problem in terms of modules or blocks. It is many times faster than BASIC. o Finally. A C program is basically a collection of functions that are supported by the C library. C is highly portable. It made Unix easy to customize and improve by any programmer that could learn the high-level C programming language. Another important feature of C is its ability to extend itself. This modular structure makes program debugging. o First. write only a small amount of new code where absolutely required by hardware differences with the new machine. Standard C: • Standardized in 1989 by ANSI (American National Standards Institute) known as ANSI C • International standard (ISO) in 1990 which was adopted by ANSI and is known as C89 • As part of the normal evolution process the standard was updated in 1995 (C95) and 1999 (C99) IMPORTANCE OF C:             A set of built-in functions and operators can be used to write any complex program. A proper collection of these modules would make a complete program. producing many useful new extensions and enhancements. We can continuously add our own functions to the C library. write a C-to-assembly language compiler for the new machine. 5 . Programs written in C are efficient and fast. With the availability of a large number of functions. and went on to experiment with modifications to the operating system. the programming task becomes simple. C language is well suited for structured programming.

memset . etc. open . . The reasons for choosing a well structured style are that:  Long programs are manageable only if programs are properly organized.common utility functions: malloc . read .  Programs are only understandable if care is taken in choosing the names of variables and functions. strcp y. calloc . – Application Source: application source and header files – Compiler: converts source to object code for a specific platform – Linker: resolves external references and produces the executable module C Standard Header Files you may want to use • Standard Headers you should know about: 6 – Stdio. close . – stdlib. memcpy .Programming style C is actually a free format language. Elements of a C Program A C development environment includes – System libraries and headers: a set of standard libraries and their header files. strtol . write .h . atoi etc – string. printf. Such a scheme becomes increasingly difficult to achieve with the size and complexity of the problem. where to place brackets or whatever.h – file and console (also a file) io: perror . etc. This means that there are no rules about how it must be typed.string and byte manipulation: strlen . strcat .  It is much easier to find parts of a program if a strict ordering convention is maintained. scanf . when to start new lines.h . For example see /usr/include and glibc.

This function is called main • int main (void) { . written in some arbitrary order. isprint . char *envp[]) • additional local and external functions and variables..h – signal handling facility: raise. etc. clock. signal. sqrt. floor. etc – time. isupport . Every C program is a collection of one or more functions. char *argv[]. – signal. though it is not POSIX. User program structure – there must be one main function where execution begins when the program is run.h – time related facility: asctime. – errno. tolower. 7 .– ctype. • int main (int argc.h – defines errno used for reporting system errors – math. The form of a C program What goes into a C program? What will it look like? The basic building block in a C program is the function.. etc.h – character types: isalnum . } • UNIX Systems have a 3rd way to define main(). One and only one of these functions in the program must have the name main(). so the simplest C program would be just a single function definition: main () { } The parentheses () which follow the name of the function must be included even though they apparently serve no purpose at this stage. exp.1 compliant int main (int argc. This function is always the starting point of a C program. etc. etc – stdint.. char *argv[]) { . uintn_t.h – math functions: ceil. time_t. }. This is how C distinguishes functions from ordinary variables..h – standard integer: intn_t.

To write a C program. A C program may contain one or more Sections Documentation Section (Comments about the program) Link Section (Header) Global Declaration Section main() Function Section { Declaration Part (Variable Declaration) Executable Part (Statements) } Subprogram section 8 . */ #include <stdio. return (0).h> int main (void) { printf ("This is my first C program. we first create functions and then put them together. } BASIC STRUCTURE OF C PROGRAM A C program can be viewed as a group of building blocks called functions.\n").FORMAT OF A SIMPLE C PROGRAM: main() Function name { // Start of program -----——— Program statements ——— } End of program /* A program that prints out the sentence This is my first C program. A function is a subroutine that may include one or more statements designed to perform a specific task.

. The subprogram section contains all the user-defined functions that are called in the main function.. There are some variables that are used in more than one function. 1. The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. The program execution begins at the opening brace and ends at the closing brace.. but are prohibited between the characters of keywords and identifiers. digit or special symbol used to represent information. All sections.. (User-defined functions) Function The documentation section consists of a set of comment lines giving the name of the program.. These two parts must appear between the opening and the closing braces. 2. Creating the program Compiling the program Linking the program with functions that are needed from the C library Executing the program. Special Characters 4. the author and other details which the programmer would like to use later. The characters in C are grouped into the following categories: 1. 1. 4..Function1 Function2 ………. Digits 3. although they may appear in any order.. User defined -functions are generally placed immediately after the main function. declaration part and 2. 3. Digits: All decimal digits 0 . 9 Special Characters 9 . The closing brace of the main function section is the logical end of the program.. Letters: Uppercase A……Z Lowercase a……z 2. The C Character Set: A character denotes any alphabet. Letters 2. All the statements in the declaration and executable parts end with a semicolon. Every C program must have one main() function section. executable part. The link section provides instructions to the compiler to link functions from the system library.. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section contains two parts. except the main function may be absent when they are not required. EXECUTING OF A ‘C’ PROGRAM Executing a program written in C involves a series of steps. White Spaces White spaces may be used to separate words. These are: 1.

Character Constants and 2. Ex: 426 +782 -8000 -7605 /* program for Integer no’s */ # include<stdio. Union. Secondary Constants we learn Array. A variable also can be stored in the memory of the computer.) Period (. c=a+b. Rules for constructing Integer Constants: a) An integer constant must have at least one digit b) It must not have a decimal point. But the contents of the variable can be changed. f) The allowable range for integer constants is -32768 to 32767. Structures. Pointers. Primary Constants & 2. e) No commas or blanks are allowed within an integer constant. d) If no sign precedes an integer constant it is assumed to be positive. printf(“value of c is %d”.) Semi colon (.c). Types of C Constants: C constants can be divided into two major categories: 1.h> void main() { int a. Enum etc.c. Secondary Constants 1. b. Variables and Keywords): A constant is a quantity that doesn’t change. This quantity can be stored at a locations in the memory of the computer. Primary Constants we learn Integer Constants. clrscr(). getch(). Real Constants.Comma (. 10 . White Space: Blank space C Tokens (Constants.) Colon (:) Question mark (?) apostrophe (‘) Quotation mark (“) Exclamation mark (!) vertical bar (|) slash (/) back slash (\) tilde (~) under score (_) dollar sign ($) percent sign (%) number sign (#) & ampersand(&) & caret(^) & asterisk(*) & minus(-) & plus sign(+) & opening angle bracket(<) & less than sign(<) & closing angle bracket(>) & greater than sign(>) & left parenthesis(( ) & right parentheses ( )) & left bracket([) & right bracket(]) & left brace({) & right brace(}) 4. c) It can be either positive or negative.

return (0).} Rules for constructing Real Constants: a) b) c) d) e) f) A real constant must have at least one digit It must have a decimal point. a single digit or a single special symbol enclosed within single inverted commas.2lf\n". printf ("%lf\n". No commas or blanks are allowed within an real constant. printf ("%d\n". a). printf ("%18.4e38. printf ("%4d\n". x). double x.583665. It can be either positive or negative. /* executable statements */ a = 1000. Ex: ‘A’ ‘I’ ‘5’ ‘=‘ / * Inputting characters A program that asks the user for 4 characters and displays them on the screen.4lf\n". If no sign precedes a real constant it is assumed to be positive. x). printf ("%5d\n". a).h> int main (void) { /* declarations */ int a. Ex: +325. The allowable range for real constants is -3. a). printf ("%3d\n". x = 100.0 -80. x). a). #include <stdio. } Rules for constructing Character Constants: a) A character constant is a single alphabet. printf ("%15. x).34 +782.578 #include <stdio. printf ("%12. printf ("\n").0lf\n". x). b) The maximum length of a character constant can be 1 character.4e38 to 3. printf ("%15lf\n".76 -760.h> int main (void) 11 .

2. return (0). letter1. letter2. } output: enter a name: lucky you entered : lucky C Keywords: Keywords are the words whose meaning has already been explained to the C compiler. code. char name. Control Instruction 1. &letter2. printf ("you entered: %c%c%c%c". auto break case char const continue default do double else enum extern float far for goto if int long near register return short signed static struct switch typedef union unsigned void while C Instructions: There are basically four types of instructions in C. letter4. float rs. &letter4). letter3. Type declaration statement is usually written at the beginning of the C program. Any variable used in the program must be declared before using it in any statement. Input/Output Instruction: This instruction is used to perform the function of supplying input data to a program (scanf() function and obtaining the output results from it ( printf() function). letter3. Type Declaration Instruction: This instruction is used to declare the type of variables being used in the program.h> int main (void) { 12 . There are only 32 keywords available in C. The keywords cannot be used as variable names. printf (" / backwards: %c%c%c%c\n". printf ("enter a name: "). &letter3. letter2.{ /* declarations */ char letter1. Example: Int bas. letter3. letter4). Trying printf and scanf A program that asks the user for two numbers and prints out the sum and the product. Arithmetic Instruction 4. letter4. letter1). 1. grossal. &letter1. scanf ("%c%c%c%c". #include <stdio. Type Declaration Instruction 2. letter2. Input/Output Instruction 3.

5 2.0056. There are four types of control instructions in C. Assignment. z. printf ("\nThe product of %lf and %lf is %lf. y. printf ("\nThe sum of %lf and %lf is %f. Control instruction: This instruction is used to control the sequence of execution of various statements in a C program.0/5 0. return (0).*. z). Multiplication 2. x*y). Character constants are stored in character variable as follows: char a.0 0. *.0 2. 4. Arithmetic Instruction: A C arithmetic instruction consists of a variable name on the left hand side of = and variable names & constants on the right hand side of =. Division 3. scanf ("%lf %lf". kot = 0. The variables and constants appearing on the right hand side of = are connected by arithmetic operators like +. &x. x. Substraction 6. -. The control instructions determine the flow of control in a program.4 The arithmetic operations are performed an order given below: 1.5 2/5. x. Sequence Control Instruction 13 . / arecalled operators.0/2 2.0 2. } 3. The variables and constants together are called operands and +. 1. b = ‘G’. y. d./* declarations */ double x. data. b. a = ‘F’. Operation Result Operation Result 5/2 2 2/5 0 5. z = x + y. The right hand side is evaluated and this value is then assigned to the variable on the left hand side. Operation between an integer and real always yields a real result. y. data = ad + kot+ 32 +5.5 2. ad = 3200. An Arithmetic operation between an integer and integer always yields an integer result. Operation between a real and real always yields a real result.\n".\n". d = ‘+’. and /. Modulo Division 4. Example: int ad.4 5/2. C allows only one variable on left hand side of =. float kot.0/5.0 0. /* executable statements */ printf ("Enter two integer numbers: "). &y).4 5. . Addition 5.0/2.

z=x*y. printf("\n the subtraction of two numbers : %d". Relational operators 3. Operators are used in programs to manipulate data and variables.z). clrscr(). printf("\n the multiplication of two numbers : %d". printf("\n the remainder of x/y is : %d". Conditional operators 7.&y). C operators can be classified into eight categories as shown below: 1.h> #include<conio. /* Example for Arithmatic operations */ #include<stdio. Increment and decrement operators 6. z=x+y.y. Selection or Decision Control Instruction 3. -.z).z).z). The unary minus operator. *. /).&x.z). scanf("%d %d". Arithmetic operators 2. a number preceded by a minus sign changes its sign. Therefore. Assignment operators 5. z=x-y. Special operators 1. Repition or Loop Control Instruction 4. multiplies its single operand by -1. } 14 . printf(" enter the values of x and y :"). They usually form a part of the mathematical of logical expressions. in effect. z=x%y. ARITHMETIC OPERATORS: C provides all the basic arithmetic operators (+. z=x/y. Bitwise operators 8.h> main() { int x. Case Control Instruction OPERATORS AND EXPRESSIONS C supports a rich set of operators. getch(). printf("\n the division of two numbers : %d". printf("\n the addition of two numbers : %d".z=0. Logical operators 4. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operator Meaning + Addition Subtraction * Multiplication / Division % Modulo division Interger division truncates any fractional part.2.

! meaning logical NOT Some examples of the usage of logical expressions are given below: 1. c.) LOGICAL OPERATORS: C has the following three logical operators. and so on. or the price of two items. and depending on their relation. exp is an expression and op is a shorthand assignment operator. if(age > 55 && salary < 1000) 2. */ #include <stdio. we may compare the age of two persons. It is equivalent to v = v op (exp). 15 . 1.5 < -10 FALSE -35 >= 0 FALSE 10 < 7+5 TRUE a+b = = c+d TRUE (only if the sum of values of a and b is equal to the sum of values of c and d. take certain decisions. C has a set of shorthand assignment operators as shown below: v op = exp. d. These comparisons can be done with the help of relational operators. e. if(number < 0 || number > 100) ASSIGNMENT OPERATORS Assignment operators are used to assign the result of an expression to a variable. where v is a varible. /* A program that makes a few changes in variable values using the assignment operator.5 <= 10 TRUE 4. For example.RELATIONAL OPERATORS: We often compare two quantities. || meaning logical OR 3.h> int main (void) { /* declarations */ int a. b. C supports six relational operators as shown below: Relational Operators Operator Meaning < is less than <= is less than or equal to > is greater than >= is greater than or equal to != is not equal to == is equal to 4. && meaning logical AND 2.

a).. /* a few more assignments */ b = a. e). a = 5. */ #include <stdio. a is now %d\n". e = 20 + a.. 16 . printf ("After ++a. a = a .b + c. /* the final values are. a = 10 + a. d. c = 10 + a.h> int main (void) { int a./* fill variable a */ a = 10. c = b = 5. d = a + a + 2.Increment and decrement / *A program showing the different uses of the increment and decrement operators. c. b. } Shorthand Assignment Operators: Statement with simple Statement with assignment operator shorthand operator a=a+1 a+=1 a=a-1 a-=1 a=a*a a * =a a = a*(n+1) a* = (n+1) a = a / (n+1) a / = (n+1) a=a%b a%=b INCREMENT AND DECREMENT OPERATORS: C has two very useful operators not generally found in other languages. These are the increment and decrement operators: + + and . a = a + a + 2. return (0). b. a = 2 + a. /* increment (++) */ /* a is incremented by 1 */ ++a. /* modify variable a few times*/ a = 20. */ printf ("a:%4d\n b:%4d\n c:%4d\n d:%4d\n e:%4d\n". a.

a is now %d\n". else x = b. a. printf ("After b=++a. a). #include<stdio. printf ("After b=++a. a. /* a is incremented and b gets the incremented a */ b = ++a. else statements as follows: a = 10. These same program can be written as shown below: x = (a >b)? a: b. a. if (a > b) x =a./* a is once more incremented by 1 */ a++. /* a is incremented but b gets the current a */ b = a++. b). a is now %d\n". } CONDITIONAL OPERATOR: A ternary operator pair “?:” is available in C to construct conditional expressions of the form exp1 ? exp2 : exp3. /* a is once more decremented by 1 */ a--.b=5. printf ("After a--. 17 . a is now %d and b is %d\n". a). a. (a>b)?a is greater: b is greater. a is now %d and b is %d\n".h> void main() { Int a=5. a is now %d and b is %d\n". return (0). To find out a number which is greater than other number. a is now %d\n". b = 15. printf ("After b=a--. b). /* decrement (--) */ /* a is decremented by 1 */ --a. This can be done by using if. b). /* a is decremented and b gets the decremented a */ b = --a. printf ("After --a. a is now %d and b is %d\n". a).. printf ("After a++. printf ("After b=a++. /* a is decremented but b gets the current a */ b = a--. b).

sizeof operator. in practice. otherwise the statement-block will be skipped and the execution will jump to the statement-x. These operators are used for testing the bits. C language provides decision making statements known as control or decision making statements. This involves a kind of decision making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly. or repeat a group of statements until certain specified conditions are met. a constant or a data type qualifier. This happens when no options or no repetitions of certain calculations are necessary. And ->). There are four type of such statements. /* A program is to show the execution of IF Statement */ 18 . Example: m = sizeof(sum). 8. 1. The sizeof Operator The sizeof is a compile time operator and. it returns the number of bytes the operand occupies. 3. Remember. The operand may be a variable.} BITWISE OPERATOR C has a distinction of supporting special operators known as bitwise operators for manipulation of data at bit level. DECISION MAKING AND BRANCHING INTRODUCTION In C program. a set of statements which are normally executed sequentially in the order in which they appear. } statement-x. when the condition is true both the statement-block and the statement-x are executed in sequence. SPECIAL OPERATORS C supports some special operators such as comma operator. pointer operators (& and *) and member selection operators ( . If the test expression is true. the statement-block will be executed. 2. Bitwise operators may not be applied to float or double. However. when used with an operand. 4. or shifting them right or left. if statement switch statement Conditional operator statement goto statement SIMPLE IF STATEMENT The general form of a simle if statement is if(test expression) { statement-block. The statement-block may be a single statement or a group of statements. we have a number of situations where we may have to change the order of execution of statements based on certain conditions.

Printf(“this is too rainy”). the control is transfered subsequently to statement-x.. If(raining=true) Printf(“ this is rainy season”). either true-block or false-block will be executed. odd /* A program that determines if an integer number is odd or even..\n".h> int main (void) { int number. &number). number). the false-block statement(s) are executed. even. scanf ("%d". In either case. : IF . not both.. Expression is true x x x x x x if = = y x is equal to y != y x is not equal to y < y x is less than y > y x is greater than y <= y x is less than or equal to y >= y x is greater than or equal to y Even vs. /* display report */ if (even) printf ("%d is an even number. immediately following the if statement are executed.h> void main(){ Int raining. In both the cases.. 19 . /* ask user for number */ printf ("Enter an integer number: ").. Getch(). /* determine if number is even and put in variable */ even = (number % 2 == 0). ELSE STATEMENT The if . The general form is if(test expression) { True-block statement(s) } else { False-block statement(s) } statement-x If the test expression is true. #include <stdio. then the true-block statement(s). else statement is an extension of the simple if statement..#include<stdio. otherwise..

else printf ("%d is an odd number.. we may have to use more than one if .. THE SWITCH STATEMENT We can design a program using if statements to control the selection... The switch statement test the value of a given variable (or expression) against a list of case values and when a match is found. If a case is found whose value matches with the value of the expression.00*(units .00 per unit excess of 600 if(units <= 200) charges = 0. a block of statements associated with that case is executed.. the value of the expression is successively compared against the values value-1..65 per unit 401 to 600 Rs. else if(unit <= 600) charges = 230 + 0. The general form of the switch statement is as shown below: The expression is an integer expression or characters.. 230 plus Rs. It takes the following general form: An electric power distribution company charges its domestic consumers as follows: Consumption Units Rates of charge 0 to 200 Rs. ELSE IF LADDER There is another way of putting ifs together when multipath decisions are involved. 0.80*(units-400). \n"... the complexity of such a program increases dramatically when the number of alternatives increases. NESTED IF . 0. block-1. then the block of statements that follows the case are executed.. . number). } return (0). However.. Each of these values should be unique within a swich statement. Value-1. There is no need to put braces around these blocks. else charges = 390 + 1. 1.. The program becomes difficult to read and follow.50 per unit 201 to 400 Rs. value-2 . Note that case labels end with a colon(:).. are statement lists. A multipath decision is a chain of ifs in which the statement associated with each else is an if. else statement in nested form as follows: 12. ELSE STATEMENT: When a series of decisions are involved.. block-2 ..: The Switch Statement is shown below: switch(expression) 20 . 0.600). C has a bult-in multiway decision statement known as a switch. 100 plus Rs.. 11.. When the switch is executed..... value-2. are constants are known as case lables..65* (units-200). 390 plus Rs.80 per unit excess of 400 601 and above Rs. else if(unit <= 400) charges = 100 + 0.5*units.

/* green light */ case 'G': case 'g': printf ("GO! \n"). &colour). default: default-blcok..h> int main (void) { char colour.. } statement-x. break. break. Unlike the previous program. /* yellow or amber light */ case 'Y': case 'y': case 'A': case 'a': printf ("CAUTION! \n").. break. /* ask user for colour */ printf ("Enter the colour of the light (R. case value-2: block-2. break.\n").G. The traffic light program (switch) A program that displays the recommended actions depending on the color of a traffic light. /* other colour */ default: printf ("The colour is not valid.Y.A): ").. #include <stdio. } return (0). .. break. break...{ case value-1: block-1. scanf ("%c". this implementation uses the switch statement.. /* test the alternatives */ switch (colour) { /* red light */ case 'R': case 'r': printf ("STOP! \n"). 21 .

. A goto is often used at the end of a program to direct the control to go to the input statement.. and must be followed by a colon.. ... Such a jump is known as backward jump. . to read further data. y... On the other hand. if the label: is placed after the goto label... statement. A label is any valid variable name. Consider the following example: main() { double x. if condition must be added.. Before goto statement.. During the running of a program when a statement like goto begin... } 16. a control structure may be classified either as the entry-controlled loop or as the 22 . The label is placed immediately before the statement where the control is to transferred...... if(test expression) goto label. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.. A program loop consists of two segments. It forms a loop. y). there may be occations when the use of goto might be desirable.. some statements will be skipped and the jump is known as a forward jump.. a sequence of statements are executed until some conditions for termination of the loop are satisfied.......... .... If the label: is before the statement goto label... is met... Backward jump label: statement.. The general forms of goto and label statements are shown below: Forward jump if(test expression) goto label.... printf(“%lf\n”... if(x < 0) goto read.... THE GOTO STATEMENT C supports the goto statement to branch unconditionally from one point to another in the program... a loop will be formed and some statements will be executed repeatedly. Although it may not be essential to use the goto statement in a highly structured language like C.. The goto requires a label in a order to identify the place where the branch is to be made... &x). label: statement. read: scanf(“%lf”..Note that a goto breaks the normal sequential execution of the program.... y = sqrt(x)... .. one known as the body of the loop and the other known as the control statement.. DECISION MAKING AND LOOPING INTRODUCTION It is possible to execute a segment of a program repeatedly by introducing a counter and later testing it using the if statement and goto statement....... Depending on the position of the control statement in the loop. In looping.} 15... the flow of control will jump to the statement immediately following the label begin:. The label: can be anywhere in the program either before or after the goto label..

the body is executed once again... A looping process. In the case of an exit-controlled loop. n). /* loop initialization */ /* the loop */ while (n <= 100) /* loop condition */ { printf ("%d ". 3. 2. #include <stdio. On exit. Such situations can be handled with the help of the do statement. /* loop body */ n = n + 1. The braces are needed only if the body contains two or more statements. in general. The takes the form: 23 . } 18. 4. the control conditions are tested before the start of the loop execution. the body of the looop may not be executed at all if the condition is not satisfied at the very first attempt. Execution of the statements in the loop. the test condition is once again evaluated and if it is true. This process of repeated execution of the body continues until the test condition finally becomes false and the control is tranferred out of the loop. Incrementing the counter. The basic format of the while statement is shown below: while(test condition) { body of the loop } The while is an entry-controlled loop statement. They are: 1. After execution of the body. THE DO . then the body of the loop is executed. Test for a specified condition for exection of the loop. the test is performed at the end of the body of the loop and therefore the body is executed unconditionally for the first time. On some occations it might be necessary to execute the body of the loop before the test is performed. A simple count from 1 to 100 /* A program that displays the numbers between 1 and 100.. The for statement 17. The C language provides for three loop constructs for performing loop operations..h> int main (void) { int n.The while statement 2.exit-controlled loop. WHILE STATEMENT In while loop a test condition is checked before the loop is executed.The do . Setting and initialization of a counter.while statement 3. If the conditions are not satisfied. it is a good practice to use braces even if the body has only one statement. However. then the body of the loop will not be executed. the program continues with the statement immediately after the body of the loop. would include the following four steps: 1. THE WHILE STATEMENT The simplest of all the looping structures in C is the while statement. Therefoere. /* loop update */ } return (0). In entry-control loop. The body of the loop may have one or more statements. The test-condition is evaluated and if the condition is true. n = 1.

printf(" 4 . char c='y'.y.x*y)..MENU ----------\n"). printf(" 2 .&x. do{ printf("--------. break. the test-condition in the while statement is evaluated. break. printf(" 1 . else printf("\n difference = %d". default: printf("\n invalid in-put"). break. SUB \n").do { body of the loop } while(test-condition). case 3: printf("\n multiplication = %d ".h> #include<conio. On reaching the do statement.. printf(" enter the two numbers :"). This process continues as long as the condition is true. the program proceeds to evaluate the body of the loop first.x-y). the do . At the end of the loop. scanf("%d %d".&y). When the condition becomes false.x+y).&choice). /* Program to demonstrate do . MUL \n"). printf(" enter your choice :"). case 2: if(x>y) printf("\n difference = %d ". DIV \n").x. case 4: if(y!=0) printf("\n division = %d ".h> main() { int choice.while program to print menu */ #include<stdio.x/y). ADD \n"). else printf("\n infinity "). clrscr(). If the condition is true.y-x). printf(" 5 . while construct provides an exit-controlled loop and therefore the body of the loop is always executed at least once. Since the test-condition is evaluated at the bottom of the loop. switch(choice) { case 1: printf("\n sum= %d ". printf(" 3 . the program continues to evaluate the body of the loop once again. case 5: exit(0). EXIT \n"). break. break. scanf("%d". the loop will be terminated and the control goes to the statement that appears immediately after the while statement. 24 .

If the condition is true. The variable i is known as loop-control variable.&c). n <= 10. increment) { body of the loop } The execution of the for statement is as follows: 1.} fflush(stdin). ++n) { ---------} . }while(c=='y'||c=='Y'). while(n <= 10) do { { ----------n = n + 1. x <= 9. test-condition. n = 1. such as i<10 that determines when the loop will exit. using assignment statements such as i=1. If the conition is satisfied. } THE FOR STATEMENT The for loop is another entry-controlled loop that provides a more concise loop control structure. the control is transferred back to the for statement after evaluating the last statement in the loop. the body of the loop is executed. otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop. x = x + 1) { printf(“%d”. clrscr(). 3. printf(" do u want to continue (y/n) :"). the control variable is incremented using an assignment statement such as i = i+1 and the new value of the control variable is again tested to see whether it saatisfies the loop condition. When the body of the loop is executed. #include<stdio. This process continues till the value of the control variable fails to satisfy the test-condition. 2. the body of the looop is again executed. n = n + 1. 25 for for(n = 1. getch(). } Comparision of the while. scanf("%c". The test condition is a relational expression. Initialization of the control variable is done first. for(x = 0.h> void main() { int x. The general form of the for loop is shown below: for(initialization. for loops While do n = 1. The value of the control variable is tested using the test-condition. } printf(“\n”). do. } } while(n <= 10). getch(). x). Now.

For example. arrays must be declared before they are used. The size in a character string represents the maximum number of characters that the string can hold..An array shares a common name. or char and the size indicates the maximum number of elements that can be stored inside the array.. x[2].subscripted variable or onedimensional array. x[n-1] The subscript begins with number 0. The type specifies the type of element that will be contained in the array. The general form of array declaration is type variable-name[size].. we can define an array name salary to represent a set of salries of a group of employees. That is x[0] is allowed. Suppose we read the following string constant into the string variable name. The general form of initialization of arrays is: 26 . the individual values are called elements. say (35. For example. salary[10] while the complete set of values is referred to as an array.. For instance. “WELL DONE” Initialization of Arrays: We can initialize the elements of arrays in the same way as the ordinaryvariables when they are declared... 40. 19) by an array variable number.ARRAYS Aset of variables of same type is called array... ONE-DIMENSIONAL ARRAYS A list of items can be given one variable name using only one subscript and such a variable is called a single . if we want to represent a set of five numbers. int group[10]. Array can be of any variable type.. declares the name as a character array (string) variable that can hold a maximum of 10 characters. For instance.. x[1]. then we may declare the variable number as follows int number[5]. and the computer reserves five storage locations and afterwards numbers are inserted as shown below: 35 number[0] 40 number[1] 20 number[2] 57 number[3] 19 number[4] Declaration of Arrays Like any other variable. float height[50]. . 20... such as int. char name[10]. A particular value is indicated by writing a number called index number or subscript in brackets after the array name. In C. single-subscripted variable xi can be expressed as x[0]. For example.. 57. float. The C language treats character strings simply as array of characters.

h> main() { int arr[6]={67. {1. The above statement can be equivalently written as static int table[2][3] = {{0. Two dimensional arrays are stored in memory as shown below: As with the singledimensional arrays.i.65.i++) printf("%3d". } TWO . 1. 0}. by surrounding the elements of each row by braces. For example: static int table[2][3] = {0.sum=0. The values in the list are separated by commas. If the number of values in the list is less than the number of elements. For example.sum).75}. static float total[5] = {0. will declare the variable number as an array of size 3 and will assign zero to each element. Two-dimensional arrays are declared as follows: type array_name [row_size][column_size].i<6. 1. return 0. clrscr(). 1. The initialization is done row by row.69.arr[i]).89.0. For instance. 0. //clrscr(). 15.i. 1}. 0}.static type array-name[size] = {list of values}.i<6. The remaining elements will be set to zero automatically. for(i=0.h> #include<conio.i++) scanf("%d". 1}}. for(i=0. } /* A program is to calculate the sum of a array */ main() { int arr[6].DIMENSIONAL ARRAYS: The data in a table can be considered as two-dimenstional array. printf("enter the elements into an array :"). 0. INITIALIZING TWO –DIMENSIONAL ARRAYS Like the one-dimensional arrays. We can also initialize a two-dimensional array in the form of a matrix asshown as: 27 . #include<stdio. 0.78. two-dimensional arrays may beinitialized by following their declaration with a list of initial values enclosed in braces. initializes the elements of the first row to zero and the secnd row to one. each dimension of the array is indexed from zero to its maximum size minus one.&arr[i]). getch(). the statement static int number[3] = {0. then only that many elements will be initialized.i++) sum=sum+arr[i].i<6. printf("\n total marks = %d ". the first index selects the row and the second index selects the column within that row. -10}. 0.75. for(i=0.

&m. printf("ENTER THE VALUES INTO MATRIX B: ").b[10][10]. scanf("%d%d".b[2][2].c[10][10]. 1.i<2.c[i][j]).i.j. } getch().&p. 0}. printf("ENTER THE SIZE OF THE MATRIX A: "). for(i=0.i<m.j++) printf("%5d". clrscr().static int table[2][3] = { {0. printf("\nthe elements of an array c :\n").j<2.i<2.j++) scanf("%d".&a[i][j]).i++) 28 .j<n.j++) c[i][j]=a[i][j]+b[i][j].c[2][2]. {1. for(i=0. for(i=0.&a[i][j]). printf("\n"). printf("enter the elements into an array a:").i++) for(j=0.i<2.q.j<2. clrscr().j.&q).j++) scanf("%d". for(i=0. for(i=0. for(i=0.p. printf("enter the elements into an array b:").j<2.i++) for(j=0. printf("ENTER THE SIZE OF THE MATRIX B: ").i++) { for(j=0.j++) scanf("%d".i<2.i++) for(j=0.i++) for(j=0.i<p. scanf("%d%d". /* Example for a Double Dimensions */ main() { int a[2][2].&n).i.n.&b[i][j]).j<2. if(m==p && n==q) { printf("ENTER THE VALUES INTO MATRIX A: ").h> void main() { int a[10][10]. int m. 0. } /* A program is to find addition of a matrices */ #include <stdio. 1} }.

i<r1.i<r1.j++) { for(k=0.i++) for(j=0. getch(). for(i=0. scanf("%d%d%d%d". for(i=0.&b[i][j]).i++) { for(j=0.c1.j.c[r][c].r2. if(c1==r2) { printf("\nmultiplication is possible").&r2.h> void main() { int a[r1][c1].b[i][j]). printf("\nenter r1.j<c1.&r1.j<n.c2"). c[i][j]=0.j<q.&c2). getch(). } printf("\n"). } MULTI . for(i=0.i<r2.k++) c[i][j]=c[i][j]+a[i][k]*b[k][j]. printf("%d\t". } /* A program is to find multiplication of matrices */ #include<stdio.&a[i][j]). printf("\nenter the 2 ele").j<c2.c[i][j]).j++) printf("%d".b[r2][c2]. printf("THE MATRIX addition is: \n").i<r2.i++) for(j=0. } } else printf("ADDITION NOT POSSIBLE").j++) scanf("%d".for(j=0.i++) { for(j=0. } } for(i=0.k<c1.j<c2.DIMENSIONAL ARRAYS 29 . for(i=0.&c1. printf("enter the 1 ele").j++) scanf("%d". } else printf("multiplication is not possible").j++) scanf("%d".c[i][j]).i.i++) for(j=0.i<m.j++) { c[i][j]=a[i][j]+b[i][j].j<c1.

Similarly table is a four-dimensional array containing 300 elements of floating-point type. Any group of characters defined between double quotation marks is a constant string. Example: “Man is obviously made to think... The array survey may represent a survey data of rainfall during the last three years from January to December in five cities. char name[30]. The general form of a multi-dimensional array is type array_name[s1][s2][s3] . The size determines the number of characters in the string-name. and float table[5][4][5][3].. Reading a Line of Text: In many text processing applications. printf(“\“Well Done!\” ”).. using the 30 ..C allows arrays of three or more dimensions.. We have learned to read a single character from the terminal. This is because the scanf terminates reading as soon as a space is encountered in input. The general form of declaration of a string variable is char string_name[size]. survey is a three-dimensional array declared to contain 180 integer type elements. Some example are: int survery[3][5][12]. The common operations performed on character strings are:  Reading and Writing strings  Combining strings together.” For example. we need to read in an entire time of text from the terminal. It is not possible to use scanf function to read a line containing more than one word.  Copying one string to another. [sm]. will output the string WellDone! Character strings often used to build meaningful and readable programs. where si is the size of the ith dimension. Some examples are: char city[10].  Extracting a portion of a string... will output the string “Well Done!” while the statement printf(“WellDone!”).  Comparing strings for equality. DECLARING AND INITIALIZING STRING VARIABLES: A string variable is any valid C variable name and is always declared as an array.. HANDLING OF CHARACTER STRINGS INTRODUCTION: A string is an array of characters.

will display the number 97 on the screen. The function takes the form x = atoi(string). strrev() reversing the string. strupr() converts lower case to upper case. string). x = ‘a’. w. printf(“%*. if the machine uses the ASCII representation. In ASCII character set. 2. x). nothing is printed. When the field width is less than the length of the string.HANDLING FUNCTIONS The C library supports a large number of string-handling functions that can be used to carry out many of the string manipulations. For example. WRITING STRINGS TO SCREEN We have used the printf function with %s format to print strings to the screen. The format %s can be used to display an array of characters that is terminated by the null character. The C labrary supports a function that converts a string of digits into their integer values. then. It takes the following 31 . 4. strlwr() converts upper case to lower case. STRING . For example. printf(“%d\n”. The integer value on the right side of the decimal point specifies the number of characters to be printed. The values from 91 to 96 are excluded using an if statement in the for loop. Following are the most commonly used string-handling functions. OPERATIONS ON CHARACTERS C allows us to manipulate characters the same way we do with numbers. strcat() Function The strcat function joins two strings together. The minus sign in the specification causes the string to be printed left-justified. name). 3. the entire string is printed. The integer value depends on the local character set of the system. Whenever a character constant or character variable is used in an expression. can be used to display the entire contents of the array name.function getchar. Function Action strcat() concatenates two strings strcmp() compares two strings strcpy() copies one string over another strlen() finds the length of a string. When the number of characters to be printed is specified as zero. the decimal numbers 65 to 90 represent upper-case alphabets (A-Z) and 97 to 122 represent lower-case alphabets (a-z). 1. the statement printf(“%s”. The following features of the %s specifications. d. To write a character in its integer representation. it is automatically converted into an integer value by the system. we may write it as an integer.*s\n”.

string1 and string2 may be string variables or string constants. strcat(destination.buf2). the statement strcpy(city.c). scanf("%s %s". clrscr(). } strcmp() Function The strcmp function compares two strings identified b the arguments and has a value 0 if they are equal. else if (ptr > 0) printf("\nbuffer 2 is greater than buffer 1\n"). If they are not. string3).h> #include<stdio. printf("diff =%d\n". getch(). getch(). strcat(destination.buf2[10]. For example. It takes the form: strcmp(string1.buf1.h> void main() { char destination[25]="This is ". clrscr(). Examples are: strcmp(“Rom”. “Ram”). ptr=strcmp(buf2. C permits nesting of strcat functions.destination). it has the numeric difference between the first non matching characters in the strings. buf1). For example. #include<string. } strcopy() Function The strcpy function works almost like a string-assignment operator. string2). else printf("buffer 2 is less than buffer 1\n").turbo).c[8] = " Turbo ".h> #include<stdio. #include<string. printf("enter two strings :"). It takes the form strcpy(string1. string2). the statement strcat (strcat (string1. string2). “DELHI”).h> void main() { char buf1[10].ptr).form: strcat(string1. if(ptr==0) printf("two strings are equal\n "). string2). printf("%s\n". int ptr. 32 . turbo[5]=" C++".

printf("%s\n".h> #include<string. char str1[10]="abcdefghi".forward). n = strlen(string).l). clrscr(). printf("After strrev(): %s\n". string).h> void main() { 33 . } strcpy(string.h> void main() { char forward[10] = "string".h> #include <string. } /* A program is to convert upper case to lower case */ #include <stdio. clrscr(). #include<stdio. char string[25]="Borland International".str1).h> #include<string. strrev(forward).h> #include<string. strlen() Function This function counts and returns the number of characters in a string.h> #include<conio.forward). l=strlen(string). printf("Before strrev(): %s\n".#include<stdio. clrscr(). where n is an integer variable which receives the value of the length of the string. getch(). } /* A program is to find the reverse of a string */ #include<stdio. getch().h> #include<conio. printf("%d\n".h> void main() { int l=0.h> void main() { char string[10]. getch().

test and maintain it. and it will be difficult to debug. clrscr(). 34 . These functions are much easier to understand. 1. So we use independent functions in main function.h> void main() { char string[25] = "BorlandInternational". C functions can be classified into two categories. Note: main is an example of user-defined function. main. getch(). strupr(string). printf("string after strlwr: %s\n".char string[25] = "BorlandInternational". Library functions and 2. strlwr(string). string). printf("string prior to strupr: %s\n".h> #include <string. Every C program can be thought of as a collection of these functions. string). debug. namely. The main difference between these two categories is that library functions are not required to be written by us whereas a user-defined function has to be developed by the user at the time of writing a program. string). and test. and scanf. printf. clrscr(). If only main function is used. namely. printf("string prior to strlwr: %s\n". getch(). We shall consider in detail how a function is designed. how two or more functions are put together and how they communicate with one another. A function performs same type of task every time. string). then the program may become too big and complex. user-defined functions. Generally we use three primary functions. printf and scanf belongs to the category of library functions. printf("string after strupr: %s\n". } /* A program is to find the converts lower case to upper case */ #include <stdio. } USER-DEFINED FUNCTIONS INTRODUCTION: A function is a self-contained block of statements that perform a task of some kind. NEED FOR LIBRARY& USER-DEFINED FUNCTIONS Every program must have a main function to indicate where the program has to begin its execution.

Variable Declaration: Varible declaration can be two types: They are: Local And Global Where a program's fingers can't reach. CATEGORY OF USER-DEFINED FUNCTIONS A user-defined function.The main function calls familier functions from C library. executable statement1. Then the main function can be called as calling function and the user-defined function is called called function. the argument list and its associated argument declarartion parts are optional. ------------------------return(expression). the main function calls the required function. Its absence indicates that no value is being returned to the calling function. Every C program can be designed using a collection of these block boxes. For example. THE FORMAT OF USER-DEFINED FUNCTION: All user-defined functions have the form given below: function-name(argument list) argument declaration. } All parts are not essential. The declaration of local variable is required only when any local variable are used in the function. Category 1: Functions with no arguments and no return values Category 2: Functions with arguments and no return values Category 3: Functions with arguments and return values. may belongs to one of the following categories. The return statement is the mechanism for returning a value to the calling function. A function can have any number of executable statements. A user-defined function is a seft-contained block of code that performs a particular task. Functions can be thought of as sealed capsules of program code which float on a background of white space. Once a function has been designed and packed. Whenever these user-defined functions are required. The user-defined functions are kept after the main function ends. it can be treated as a ‘block box’ that takes some data from the main program and returns a value. White space is the name given to the white of an imaginary piece of paper 35 . Some may be absent. executable statement1. { local variable declarations. The function of specific type can be prepared by the user called user-defined function. The inner details of operation are invisible to the rest of the program. All that the program knows about a function is: What goes in and what comes out. This is an optional statement. depending on whether arguments are present or not and whether a value is returned or not. and are connected together by means of function calls. a C program is nothing more than a collection of functions and declarations. From the computer's point of view.

shilpa().. then it does not return any value to the main function. Global variables are available everywhere. } shilpa() { printf(“I too love India. Local Variables: Local variables are more interesting. main() { printf(“I love India. The global white space is only the gaps between functions.\n”). If there is no calculations in the calling function. 1. it does not receive any data from the calling function. Similarly. neha(). then global variables (data storage areas which also float in this sea) can enter any ship and also enter anything inside any ship (See the diagram). ARGUMENTS BUT NO RETURNVALUES: When a function has an argument. In effect. To use the ship analogy: if it is imagined that on board every ship (which means inside every function) there is a large swimming pool with many toy ships floating inside. then local variables will work anywhere in the swimming pool (inside any of the toys ships. NO ARGUMENTS AND NO RETURN VALUES When a function has no arguments. when it does not return a value. 2. the calling function does not receive any data from the called function. } The output of the above program when executed would be as under: o/p: I love India. but can not get out of the large ship into the wide beyond. but one which is restricted to being inside a particular function. The swimming pool is just like a smaller sea. it receives data from the terminal and it is transferred to the called function. there is no data transfer between the calling function and the called function. They can not enter just any region of the program because they are trapped inside blocks. 36 .\n”). Do you love India? I too love India.upon which a program is written. they are created when a program is started and are not destroyed until a program is stopped. not the gaps inside functions. Global Variables: Global variables are declared in the white space between functions. If every function is a ship floating in this sea of white space. } neha() { printf(“Do you love India?\n”). in other words the spaces and new line characters which are invisible to the eye.

b. it receives data from the terminal and they are transferred to the called function. i++) printf("%c". printf("\n"). &b. Immediately after the closing brace the control is returned to the calling function. scanf("%d %d %d". These arguments must be in parentheses. sum. then it returns the to the main function for further processing or displaying. printf("Enter a character\n"). printf("Enter any three numbers\n"). Therefore. &a. &c). printline(ch). then the compiler would still treat them as different variable since they are in different function. c). In this user-defined function nothing is to be returned. getch(). This argument can be called actual argument. 3. } printline(char x) { int i. clrscr(). If you use actual argument in the user defined function. The arugment for parameter may be a variable or character constant. 37 . printline(ch). Example: main() { char ch. scanf("%c".The mechanism used to convey information to the user-defined function is the arugument or parameter. b. Example: /* Sending and receiving values between calling and called functions */ main() { int a. it is not necessary to use the return statement. sum). In the User defined function we find another argument called formal argument which must be declared in the parenthesis. i <= 25. clrscr(). ARGUMENTS WITH RETURN VALUES When a function has arguments. printf("\nWelcome to Neha Computers\n"). for(i=1. printf("Sum = %d\n". } The output will be under the control of the user. sum = calsum(a. &ch). c. clrscr(). The calculations are done in the calling function. x). if ch is * then the the output will be as under: In this program ch can be called as argument or paramenter. It receives argument from the terminal. This argument is transferred to the user-defined function. getch().

FUNTIONS RETURNING NOTHING We have seen earlier that in many occations. functions do not return any value. clrscr(). at the most. getch(). While it is possible to pass to the called function any number of values. } float mul(x. Example: main() { float a.0. y. } RETURN VALUES AND THEIR TYPES: A function may or may not send back any value to the calling function. b)). If it does. the called function can only return one value per call. y. it is done through the return statement. d = x + y + z. or return (expression).} calsum(x. printf("%f\n". } 38 . { return(x*y). } In this program it returns a floating value. mul(). } void gospel() { Printf(“What a nice person you are!\n”). b = 3. b. { int d. y) float x. return(d). The return statement can take one of the following forms: Return . y. z) int x. They perform only some printing. printf(“I want to be your friend\n”). This is made possible by making use of the keyword void.0. a = 10. Example: main() { void gospel(). mul(a. z.

if(n ==1) return(1). CALL BY VALUE: 39 ... where a function calls itself.. } Let us see how the recursion works. return(fact). else fact = n*factorial(n-1)..... fact = 3 * factorial(2). Since the value of n is not 1..... will be executed with n = 3.... Assume n = 3.. That is.. { int fact. The expression on the right-hand side includes a call to factorial with n = 2. we must have an if statement somewhere to force the function to return without the recursive call being executed..NESTING OF FUNCTIONS C permits nesting functions freely. There is in principle no limit as to how deeplly functions can be nested.. . A very simple example of recursion is the evaluation of factorials of a given number. RECURSION When a called function in turn calls another function a processng of ‘chaining’ occurs.. This time... main can call function1.. the statement fact = n * factorial(n-1). which calls function3. which calls function2. When we write recursive functions. The sequence of operations can be summarized as follows: fact = 3 * factorial(2) = 3 * 2 * factorial(1) =3*2*1 =6 Recursion function can be effectively used to solve problems where the solution is expressed in terms of successively applying the same solution to subsets of the problem.. Recursion is a special case of this process. the function returns 1.. will be evaluated. This call will return the following value: 2 * factorail(1) Once again..1. factorial is called with n = 1..... The factorial of a number n is expressed as a series of repetitive multiplications as shown below: factorial of n = n(n-1)(n-2) .... A function to evaluate factorial of n is as follows: Factorial(n) int n.

b). } void swap(int x. return 0.int*).a. temp=x. printf(“\n enter the 2 integers”). getch(). *q=*p-*q.p.q). scanf("%d %d". } void swap(int* p. /* Example for call by reference */ #include<stdio.j.b. swap(a. *p=*p-*q. } CALL BY REFERENCE: The Changes made in the formal arguments will reflect to actual parameters(arguments). getch().&j).b).&a.a. y=temp.int).&j).&b). swap(&i.The changes made in the formal arguments will not reflect to atual arguments. void swap(int. } 40 . printf("values of i and j after function call: i=%d j=%d".h> #include<conio. int y) { int temp. printf(“\n before swapping a=%d \t b=%d”. printf("enter the values of i and j :"). x=y. scanf(“%d%d”. /* Example for Call by Value */ void main() { int a. printf("values of p and q in function : p=%d q=%d".j). main() { int i. clrscr().int *q) { *p=*p+*q. printf(“\n after swapping a=%d \t =%d “.i.h> void swap(int*.&i.b).

return 0. } printf("\nAfter swapping: a = %d.h> void swap(int *. temp = a. a=a/b. Internal variables are those which are declared within a particular function.b). External variables 3.b.&b).int *b){ int *temp. a=a*b. Static variables 4. 1. *b=*temp. b=6 After swapping: a = 6. AUTOMATIC VARIABLES: 41 . swap(&a. *a=*b. Automatic variables 2. scanf("%d%d". depending on the place of their declaraton. as internal (local) or external (global).&b). So longevity has a direct effect on the utility of a given variable. //or a=(a*b)/(b=a).a.int *). } // a=a^b. ////a=a*b. // a^=b^=a^=b. int main(){ int a. or a=a+b – (b=a).a.&a. A variable in C can have any one of the four storage classes: 1. b=%d".Swapping program in c using function using Temporary variable #include<stdio.b=a/b.b). printf("Before swapping: a = %d. while external variables are declared outside of any function. The scope of variable determines over what parts of the program a variable is actually available for use (active). b=%d".or Sample output: Enter any two integers: 3 6 Before swapping: a = 3. printf("Enter any two integers: "). // b=a^b. Register variables We shall briefly discuss the scope and longevity of each of the above class of variables. void swap(int *a. The variables may also be broadly categorized. The computer stores the variable either in RAM or CPU register. Because variable has certain default storage class. b=6 STORAGE CLASSES In C programs we declare only type of variable but we dont define its storage class. Longevity refers to the period during which a variable retains a given value during execution of a program (alive). // a=a^b.

hence the name automatic.i). { { { printf("\n %d". the storage class of the variable number in the example below is automatic. } void main() { int i=1. 42 .i). ------------------------------------} One important feature of automatic variables is that their value cannot be changed accidentally by what happens in some other function in the program. { int i=2. printf("\n %d". Becaue of this property. They are created when a function is called and destroyed automatically when the function is exited. Automatic variables are therefore private (or local) to the function in which they are declared. } printf("\n %d". main() { int number. main() { auto int number.i). } printf("\n %d". } printf("\n %d". /* A program is to initialize the automatic variable */ void main() { auto int i=1. It works within the blockuntil the control remains within the block in which the variable is defined. clrscr(). { int i=3.i). clrscr().i). } getch(). automatic variables are also referred to as local or internal variables.Automatic variables are declared inside a function in which they are to be utilized.i). --------------------} we may also use the keywords auto to declare automatic variables explicitly. For instance. } printf("\n %d". These variables are stored in RAM. These variables must be initialized otherwise an unpredictable value is stored in the variable which is often called a garbage value.

getch(). In case a local variable and a global variable have the same name. } void decrement() { i=i-1. getch().i). } int y=31. printf("\n %d %d". void decrement(). global variables can be accessed by any function in the program. */ int x=10. } 2. printf("\ni=%d". the local variable will have precedence over the global one in the function where it is declared. void main() { clrscr(). } int x=21. printf("\n on incrementing i= %d". increment().i). Extern int y. increment().x. They are also known as global variables. decrement(). External variables are declared outside the main function. printf("\n on decrementing i= %d".i). void increment().y). void main() { extern int y. } void increment() { i=i+1. EXTERNAL VARIABLES: Variables that are both alive and active throughout the entire program are known as external variables. /* A program is to initialize the extern variable */ int i.getch().Unlike the local variables. If global variable is not initialized then it takes 0 value as default. decrement(). 43 . clrscr().

except that they retain existence (alive) throughout the remainder of the program. /* A program is to initialize the static variable */ void main() { clrscr(). i=i+1. display(). the value of static variables persists until the end of the program. } increment() 44 . increment(). } increment() { auto int i=1. increment(). printf("\n%d ". A static variable may be either an internal type or an external type.void main() { int x=20. getch(). } 3. The scope of internal static variables are extend upto the end of the function in which they are defined. } display() { printf("\n %d". internal static variables are similar to auto variables.x). static float y.i). printf("%d\n". clrscr(). increment().x). STATIC VARIABLES: As the name suggests. getch(). depending on the place of declaration. increment(). increment(). A variable can be declared static using the keyword static like static int x. increment(). } */ void main() { clrscr(). getch().

.. The keyword struct declares a structure to hold the details of four fields.....{ static int i=1. such as int or float. number of pages. /* Program is to initialize the register variable */ void main() { register int i....i).. author. . instead of keeping in the memory (where normal variables are stored).. register int count. and price. data_type member2...i++) printf("\n%d"... These fields are called structure elements or members. }.... i=i+1.... clrscr(). keeping the frequenlty accessed variables (e... author. The general format of a structure definition is as follows: struct tag_name { data-type member1. We can define a structure to hold this information as follows: struct book { char title[20]. } Consider a book database consisting of book name.. } 4... and price. Since a register access is much faster than a memory access. printf("%d\n". However. C supports a constructed data types known as structure.i<=10. float price... pages. Each member may belongs to a different type of data.. ... namely title.. char author[15].. int pages... for(i=0....i)..... 45 . loop control variables) in the register will lead to faster execution of programs... Fortunately. if we want to represent a collection of data items of different types using a single name. which is a method of packing data of different types.. then we cannot use an array.. getch().REGISTER VARIABLES: We can tell the compiler that a variable should be kept in one of the machine’s registers.g.... } STRUCTURES We have seen that arrays can be used to represent a group of data items that belongs to the same type....

We can also use scanf to give the values through the keyboard.m2. “BASIC”).m3. printf("enter m1:").m1. float total.&b1.50.m2.b1.’ which is also known as ‘dot operator’ or ‘period operator’. printf("\n %s \n %d \n %d \n %d \n %f ".m3. The members themselves are not variables.name. scanf("%s". 3. #include<stdio.m1). In defining a structure you may note the following syntax: 1. 46 . book1. scanf("%d". printf("enter m3:").m3.b1.The tag name such as book can be used. 2. }. GIVING VALUES TO MEMBERS We can assign values to the members of a structure in a number of ways. each member is declared independently for its name and type in a separate inside the template. “Balaguru swamy”). scanf(“%d”.m1+b. book1.title).m2+b. strcpy(book1.total=(float)b.m2).book is the name of the strurcture and is called the structure tag. scanf("%d". book1. float result. clrscr(). printf("enter m2:"). They should be linked to the structructure variables in order to make them meaingful members.price = 28. &book1. While the entire declaration is considered as a statement. printf("enter name:"). scanf(“%s”. int m1. The link between a member and a variable is established using the member operator ‘.h> #include<conio. strcpy(book1.result). } void main() { struct book b1. result=sum(b1). The template is terminated with a semicolon. scanf("%d". return b. Here is how we would assign values to the members of book1. float sum(struct book b) { b.b1.m3).total.author.&b1.title.name).h> struct book { char name[10]. getch().price is the variable representing the price of book1 and can be treated like any other ordinary varible.pages = 250.&b1.b1.b1. For example: book1.pages).

static struct st_record student2 = {53. . ..75}. However. float height... }. } COMPARISION OF STRUCTURE VARIABLES: Two variables of the same structure type can be compared the same way as ordinary variables.75}. main() { static struct st_record student2 = {53..height.. 170.. then the following operations are valid: Operation person1 = person2 47 Meaning Assign person2 to person1 ...... 180. If person1 and person2 belong to the same structure. a structure must be declared as static if it is to be initialized inside a function.60}..75 to student..75}...60}.... } Another method is to initialize a structure variable outside the function as shown below: struct st_record /* No static word */ { int weight... The following statements initialize two structure variables main() { struct st_record { int weight. main() { static struct st_record { int weight..weight and 180. float height. 170. } student1 = {60.. float height. static struct st_record student1 = {60. ------------------------} This assigns the value 60 to student.. } student = {60. ......STRUCTURE INITIALIZATION: a structrue variable can be initialized. . 180.. 180..

Compare all members of person1 and and return 1 if they are equal.\ #include<stdio. . we may use a template to describe student name and marks obtained in various subjects and then declare all the students as structure variables..name)... each element of the array representing a structure variable. }. . 36. int subject3. {75. This declares the student as an array of three elements student[0]. For example: struct class student[100]. ARRAYS OF STRUCTURES We use structures to describe the format of a member of related variables.. int subject2.. person1 != person2 Return 1 if all the members are not 0 otherwise. 71}}.. 68. In such cases. and student[2] and initializes their members as follows: student [0]. {57. defines an array called student. student [0].. 69}..i++) { printf("\n enter name : ")..h> void main() { struct book { char name[10].subject1 = 45. for(i=0...h> #include<conio. 48 . main() { static struct marks student[3] = {{45.subject3 = 71.subject2 = 68. struct book b[5]... int i.. in analysing the marks obtained by a class of students. struct marks { int subject1.b[i]. we may declare an array of structures. scanf("%s". int pages. student[1]. }. For example.person1 == person2 person2 equal. 53. float price. clrscr()... Each element is defined to be of the type struct class. 81}... 0 otherwise. Student [2].i<5. that consists of 100 elements.

struct marks { int number.price. scanf("%f". and subject[2]. } linkfloat() { float a=0. basic pay and three kinds ofallowances. printf("\n enter pages :" ). subject[0].subject[2]. Here.i<5.printf("\n enter price : ").b[i]. STRUCTURES WITHIN STRUCTURES Structures within a structrue means nesting of structures. Similarly.pages). b=&a. We have already used arrays of characters inside a structure. the member subject contains three elements. getch().pages). int da. struct salary { char name[20]. char dept[10]. the name student[1]. // suppress the warning . would refer to the marks obtained in the third subject by the second student.price). We can group all the items related to allowance together anddeclare them under a sub structure as shown below: struct salary { char name[20]. 49 . int ca. subject[1]. scanf("%d".&b[i]. department. These elements can be accessed using approprite subscripts. }student[2].&b[i]. This structure defnes name. we can use single or multi-dimentional arrays of type int or float.*b. For example.variable not used } ARRAYS WITH IN STRUCTURES: C permits the use of arrays as structure members.b[i].name. } for(i=0. Let us consider the following strucutrue defined to store information about the salary of employees. float subject[3].b[i]. int basic. // cause emulator to be linked a=*b.i++) printf("\n %s \n %f \n %d ". }employee. Nesting of structures is permitted in C.

clrscr(). }. printf("\n city = %s pin=%d ".e. getch(). int hra.name."nagpur".a.h> void main() { struct book { 50 .char dept[10].e. printf("\n name = %s phone=%s ". } Structure Pointer: #include<stdio.ca.phone). struct emp { char name[20].e.allowace."531046".hra employee. struct { int da. /* Example for Structure with in structure */ #include<stdio. struct address a.a. int pin. An innner-most member in a nested structure can be accessed by chaining all the concerned structure variables with the member using dot operator. struct emp e={"sunilkumar". The salary structure contians a member named allowance which itself is a structure with three members.h> void main() { struct address { char phone[10].pin). int ca. hra.allowance.h> #include<conio. }. and ca can be referred to as employee. char city[25]. } employee.da employee.h> #include<conio.e.allowance. } allowance. The members contained in the inner structurenamely da.1238}.city.a.

b2=&b1. The union contains three members. struct book b1={"basic". we can use only one of them at a time. } code.b1. int pages. printf("\n pages2 = %d". printf("\n price1 = %f". each member has its own storage location. In structures. clrscr().To access a union member. However.130. char c. printf("\n name1 = %s". That is.c are all valid member variable. This implies that. } UNIONS: Unions are a concept borrowed from sturectures and therefore follow the same syntax as structures.x ------------------In declaration the member x require 4 bytes which is the largest among the members.price). printf("\n price2 = %f". storage of 4 bytes 1000 1001 1002 1003 --c -------------. In union any one of its members at a time can be used. there is major distinction between them in terms of storage. we can use the same syntax that we use for structure members.00. it can handle only one member at a time. a union can be declared using the keyword union as follows: union item { int m. #include<stdio. each with a different data type.b1.550}. whereas all the members of a union use the same location. However. }. Like structures. All the three variables share the same address. This declares a variable code of type union item.b2->price). getch(). float x.name).h> void main() { union book 51 . printf("\n pages1 = %d". printf("\n name2 = %s". irrespective of its size.m -------------------------------------------------------------------. code.x code.b2->pages). although a union may contain many members of different types.pages). This is due to fact that only one location is allocated for a union variable.b2->name).h> #include<conio.m code. struct book *b2. float price.b1.char name[10].

price). printf("\n address of price1 = %u". printf("\n address of name2 = %u". printf("\n price2 = %f".b1.person2. printf("\n address of pages2 = %u".name). printf("\n pages2 = %d".price).name).pages).&b1.name).&b2. printf("\n address of pages1 = %u".pages). scanf("%f". printf("\n enter price :"). }.&b2. printf("\n address of name1 = %u".pages). printf("\n\n enter name :").b1.widowed.b1. The first part declares the data type and specifies it’s possible values.&b1.b2.h> 52 . union book b1. These values are called “enumerators” #include<stdio.b2.b2.&b1.name). printf("\n enter name :").pages).price). scanf("%d". }.name). printf("\n name1 = %s".&b2. printf("\n name2 = %s".&b2.price).married.price).name).divorced. scanf("%f". float price. The format of the enum definition is similar to that of a structure.pages).b2. scanf("%s". printf("\n enter pages :").&b1.pages). printf("\n address of price2 = %u".{ char name[10]. printf("\n price1 = %f". } Enum It gives you an opportunity to invent your own data type and define what values the variable of this datatype can take. clrscr().h> #include<conio.&b1.b2. Enum mar_status person1.b1.&b2. printf("\n enter price :"). printf("\n pages1 = %d". getch(). printf("\n enter pages :"). Example: Enum mar_status{ Single. int pages. scanf("%d".price). scanf("%s".

age).bs=18765. 1. Pointers are more efficient in handling the data tables. basic salary = %f". printf("\n printf("\n printf("\n printf("\n } name = %s ". POINTERS INTRODUCTION: Pointers are another important feature of C language. 2.e1.name). has a number called address associated with it. e1. A pointer enables us to access a variable that is defined outside thefunction. A computer system having 1KB memory will have its last address as (1024-1) 1023."poonam bajwa"). 5. They increase the execution speed.bs). There are a number of reasons for using pointers. Since. 4. an appropriate location to hold the value of the variable. clrscr().h> void main() { enum emp_dept { assembly. the addresses are numbered consecutively. enum emp_dept dept.name. e1. strcpy(e1. struct employee e1. float bs. getch(). The computer’s memory is a sequential collection of ‘storage cells’. Although they may appear a little confusing for beginner. }.age=22. manufacturing. as well as the values of a the variables that are associated with it. 53 . accounts. somewhere in the memory.e1. The use of a pointer array to character strings results in saving of data storage space in memory. Pointers reduce the length and complexity of a program.e1. The real power of C lies in the proper use of pointers. e1. Each cell. int age. 3. but they are a powerful tool and handy to use once they are mastered. age= %d ". stores }. Whenever we declare a variable.dept=manufacturing. UNDERSTANDING POINTERS: We know that computers use their memory for storing the instructions of a program.00. the system allocates.#include<string.e1. starting from zero. The last address depends on the memory size.dept). department = %d". commonly known as a byte. struct employee { char name[15]. Typically.

Assigning an absolute address to a pointer variable is prohibited. nothing but a variable in which address of another variable is stored. declares the variable p as a pointer variable that points to an integer data type. This tells the compiler three things about the variable pt_name. That is. This is known as pointer initialization. For example. ACCESSING A VARIABLE THROUGH ITS POINTER 54 . ACCESSING THE ADDRESS OF A VARIABLE The address of a variable can be known by using the operator &. A pointer variable can be initialized in its declaration itself. The asteris (*) tells that the variable pt_name is a pointer variable. 3. The pointer operator availble in C is ‘ * ’. corresponding type of data. This statement instructs the system to find a location for the integer variable quantity and puts the value 179 in that location. 1. The ‘value at address’ operator is also called ‘indirection’ operator. they can be assigned to some variables which can be stored in memory. it can be made to point to a variable using an assignment statement such as p = &qty. Let us assume that the system has chosen the address location 786 for quantity. not *p. which causes p to point to qty. like any other variable. pt_name needs a memory location. For example p = 5368. The & operator can be remembered as ‘address of’. It gives the value stored at a particular address. Before a pointer is initialized. *p = &x. is perfectly valid. Since memory addresses are simply numbers. int x. DECLARING AND INITIALIZING POINTERS The declaration of a pointer variable takes the following form: data type *pt_name. called ‘value at address’. Once a pointer variable has been declared. Remember that the type int refers the data type of the variable being pointed to by p and not the type of the value of the pointer. A pointer is. Such variables that hold memory addresses are called pointers. Note carefully that this is an initialization of p. this location will have its own address number. it should not be used. For example.every byte has a unique address number. pt_name points to a variable of type data type. 2. would assign the address 786 to the variable p. p now contains the address of qty. It declares x as an integer variable and p as a pointer variable and then initializes p to the address of x. Example: int *p. the statement p = &qty.

because p is the address of qty. n. y = (*p1) + (*p2). say 2800. if p1 is an integer pointer with an initial value. *p returns the value of the variable qty. For an IBM PC. POINTER INCREMENTS AND SCALE FACTOR The pointer can be incremented like p1 = p1 + 1. are equivalent to n = *&qty. however. then after the operation p1 = p1 + 1. This length is called the scale factor. an expression like p1++. Remember. Thus the value of n would be 179. That is. its value is increased by the length of the data type that it points to. the pointer returns the value of the variable of which the pointer value is the address. The fourth line contains the indirection operator *. the sizeof(x) returns the number of bytes needed for the variable. which is turn is equivalent to n = qty.Once a pointer has been assigned the address of a variable. sum = sum + (*p1). the length of various data (scale factor) types are as follows: characters 1 byte integer 2 bytes floats 4 bytes long integers 4 bytes doubles 8 bytes We can find the number of bytes needed for a variable by making use of the sizeof operator. and so on. n = *p. will cause the pointer p1 to point to the next value of its type. qty = 179. The two statements p = &qty. For example. the value of p1 will be 2802. then the following statements are valid. *p. pointer variables can be used in expressions. For example. and not 2801. p = &qty. POINTER EXPRESSIONS Like other variables. POINTERS AND ARRAYS 55 . if p1 and p2 are properly declared and initialized pointers. In this case. int qty. The second line assign the value 179 to qty and the third line assigns the address of qty to the pointer variable p. n = *p The first line declares qty and n as integer variables and p as a pointer variable pointing to an integer. When the operator * is placed before a pointer variable in an expression. For example. The * can be remembered as ‘value at address’. you can access the value of the variable using the pointer. if x is a variable. when we increment a pointer.

each pointer pointing to a particular name as shown below: name[0] -------> New Zeeland name[1] -------> Australia name[2] --------> India 56 . “Australia”.When an array is declared. This is equivalent to p = &x[0]. This says that the name is a table containing three names. 43. 62}. we can make it a pointer to a string of varying length. That is. the five elements will be stored as follows: Elements Value Address x[0] 25 1000 x[1] 43 1002 x[2] 38 1004 x[3] 92 1006 x[4] 62 1008 The name x is defined as a constant pointer pointing to the first element. x[0] and therefore the value of x is 1000. each with a maximum length of 25 characters (including null character). declares name to be an array of three pointers to characters. we can access every value of x using p++ to move from one element to another. Suppose we declare an array x as follows: static int x[5] = {25. For example. Suppose the base address of x is 1000 and assuming that each integer requires two bytes. the location where x[0] is stored. 38. x = &x[0] = 1000 If we declare p as an integer pointer. The relationship between p and x is shown below: p = &x[0] (= 1000) p+1 = &x[1] (= 1002) p+2 = &x[2] (= 1004) p+3 = &x[3] (= 1006) p+4 = &x[4] (= 1008) POINTERS AND CHARACTER STRINGS One important use of pointers is in handling of a table of strings. Consider the following array of strings: char name[3][25]. “India” }. static char *name[3] = { “NewZealand”. We know that rarely the individual strings will be of equal lengths. The compiler also defines the array name as a constant pointer to the first element. then we can make the pointer p to point to the array x by the following assignment: p = x. Therefore. The total storage requirements for the name table are 75 bytes. The base address is the location of the first element (index 0) of the array. 92. the complier allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. instead of making each row a fixed number of characters.

Since p represents the address of x. The name product represents the address of its zeroth element. The statement *p = *p +10. This statement declares product as an array of two elements. Therefore. POINTERS AND FUNCTIONS When we pass addresses to a funtion. POINTERS AND STRUCTURES We know that the name of an array stands for the address of its zeroth element. The same thing is true of the names of arrays of structure variables. means ‘add 10 to the value stored at the address p’. } When the function change() is called. the output of the program will be 30. the variable p is declared as a pointer and therefore p is the address of the variable x. change(&x). The function which is called by ‘reference’ can change the value of the variable used in the call. Inside change(). Suppose product is an array variable of struct type. the parameters receiving the addresses should be pointers. *ptr. printf(“%d\n”. int number. The assignment ptr = product. The process of calling a function using pointers to pass the addresses of variable is known as call by reference. That is. } product[2]. the pointer ptr will now point to product[0]. Consider the following code: main() { int x. ptr -> name ptr -> number 57 . each of the type struct inventory and ptr as a pointer to data objects of the type struct Inventory. Its members can be accessed using the following notation. float prince. is passed into the function change(). the value of x is changed from 20 to 30. Consider the following declaration: struct inventory { char name[30]. }c hange(p) int *p. would assign the address of the zeroth element of product to ptr. x = 20. the address of the variable x. not its value. x).The character arrays with the rows of varying length are called ragged arrays and are better handled by pointers. not 20. { p* = *p + 10.

ptr -> price
The symbol -> is called the arrow operator and is made up of a minus sign and a greater
than sign. Note that ptr -> is simply another way of writing product[0].
When the pointer ptr is incremented by one, it is made to point to the next record, i.e.,
product[1]. The following for statement will print the values of members of all the elements
of product array.
for(ptr = product; ptr < product+2; ptr++)
printf(“%s %d %f\n”, ptr -> name, ptr -> number, ptr -> price);
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[10];
float price;
int pages;
};
struct book b1={"basic",130.00,550};
struct book *b2;
clrscr();
b2=&b1;
printf("\n name1 = %s",b1.name);
printf("\n price1 = %f",b1.price);
printf("\n pages1 = %d",b1.pages);
printf("\n name2 = %s",b2->name);
printf("\n price2 = %f",b2->price);
printf("\n pages2 = %d",b2->pages);
getch();
}

Preprocessor
Before a C program is compiled,it is passed through the another proram is called “Pre
processor”
The Pre processor works on the source code and creates ‘Expanded Source Code’, which is
stored in
‘*.I’.
This expanded source code is sent to compiler for compilation.
Pre processor directives begins with a ‘# ‘ symbol.
Some of the pre processor directives are:
1. Macro Expansion.
2. File Inclusion.

MACRO
Macro is a Pre-processor directive which is used to declare symbolic constants.
Example: # define UPPER 25
The above statement is called ‘Micro Defination’(Macro), ‘UPPER’ is called ‘ MACRO
TEMPLATE’
And 25 is called corresponding ‘macro expansion’.
It is customary to use capital letters for micro template.
Macro definition never to be terminated by a semicolon.
Macro can have arguments.
Example:

58

# define AREA(x) (3.14 *X *X)
Main()
{
Float r1=6.25,a;
a=AREA(r1);
printf(“Area is =%f”,a);
}

MACROS Vs Function
In a micro call preprocessor replaces the micro template with it’s micro expansion.
In a function call, the control is passed to function along with certain arguments, after
performing the talks in that fun a useful value is returned back.
Macros make the program run faster but increase the program size.
Function make the program smaller and compact but takes time to passing the control
between functions.

File Inclusion
This directive causes one file to be included in another file. There are two ways to write
# include<filename.h>
# include “filename.h”

The Build Process
C Source code
(PRI.C)
Pre proceesor

Expanded Source
code(PRI.I)

compiler

Assembly code
Assembler

Re locatable Object
code

Object code for library

Linker

Executable code

FILE MANAGEMENT IN C:
INTRODUCTION:
A file is a place on the disk where a group of related data is stored. C supports a number of
functions that have the ability to perform basic file operations, which include:
1. naming a file,

59

2.
3.
4.
5.

opening a file
reading data from a file
writing data to a file
closing a file

The C library uses the following High Level I/O functions:
Function name
Operation
fopen()
Creates a new file for use
Opens an existing file for use
fclose()
Closes a file which has been opend for use
getc()
Reads a character from a file
putc()
Writes a set of data values to a file
fprintf()
Writes a set of values from a file
fscanf()
Reads a set of data values from a file
getw()
Reads an integer to a file
putw()
Writes an integer to a file
fseek()
Sets the position to a desired point in the file
ftell()
Gives the current position in the file
(in terms of bytes from the start)
rewind()
Sets the position to the beginning of the file.
Opening a file:
Before we can write information to a file on a disk or read it, we must open the file. Opening
a file establishes a link between the program and the operating system. We provide the
operating system with the name of the file
and whether we plan to read or write to it. The link between our program and the operating
system is a structure called FILE which has been defined in the header file “stdio.h”
(standing for standard input/output header file). When we request the operating system to
open a file, we attach a pointer to the Structure
FILE. That is why, we make the following declaration before opening the file,
FILE *fp;
Each file we open will have its own FILE structure. The FILE structure contains information
about the file being used, such as its current size, its location in memory etc. More
importantly it contains a character pointer which
points to the character that is about to get read. Now let us understand the following
statements,
FILE *fp;
fp = fopen(“pr1.c”, “r”);
fp is a pointer variable, which contains address of the structure FILE ,which has been
defined in the header file “stdio.h”.
fopen() will open a file “pr1.c” in ‘read’ mode, which tells the C compiler that we would be
reading the contents of the file. Note that “r” is a string and not a character; hence the
double quotes and not single quotes. In
fact, fopen() performs three important tasks when you open the file in “r” mode:
1. Firstly it searches on the disk the file to be opened.
2. If the file is present, it loads the file from the disk into memory.
If the file is absent, fopen() returns a NULL. NULL is a macro defind in “stdio.h” which
indicates that you failed to open the file.
3.It sets up a character pointer which points to the first character ofthe memory where the
file has been loaded.

60

There has to be a way to break out of this while. when fgetc() encounters this special character. if(fp == NULL) { puts(“Cannot open file”). instead of returning the character that it has read. When reading from the file. While opening the file in “r” mode. If the file exists. advances the pointer position so that it now points to the next character. The tasks performed byfopen() when a file is opened in each of these modes are also mentioned. End of the file is signified by a special character. and returns the character that is read. fgetc() reads the character from current pointer position. There should be a break whenever we reach the end of the file. this may happen because the file being opened may not be present on the disk at all. which we collected in the variable c. Similarly. } } Closing the file: When we have finished reading from the file. The EOF macro has been defind in the file “stdio. we need to close it. while opening the file for writing fopen() may fail due to a number of reasons. c = fgetc(fp). like. the file may not be opened.c”. when it is created. whose ascii value is 26. as we have seen the file’s contents are brought into memory and a pointer points to the very first character. loads it into memory and sets up a pointer which points to the first character in it. We have the used the function fgetc() within an indefinite while loop.h” main() { FILE *fp. fp = fopen(“pri. #include “stdio. or the disk may be write protected and so on.Reading from a file: Once the file has been opened for reading using fopen(). And you obviously cannot read a file which doesn’t exist. This character is inserted beyond the last character in the file. The read the file’s contents from memory there exists a function called fgetc(). This has been used in our sample program through. fclose(fp). This character can also be generated from the keyboard by typing ctrl Z. exit(). This is done using the function fclose() through the statement. Trouble in opening a file: There is a possibility that when we try to open a file using the function fopen(). “r” Searces file. “r”). If the file does’t exist it returns 61 . disk space may be insufficient to open a new file.h”. it returns the macro EOF. File opening modes: A file can be opened in one of several modes.

out Data structure of a file is defined as FILE in the library of standard I/O function definitions. If the file exists. a new file is created. “r+” Serches file. writing new contents. If the file exits. Operations possible . It may contain two parts. “a+” Searches file. if uanble to open file. DEFINING AND OPENING A FILE If we want to store data in a file in the secondary memory. Operations possible . Operations possible . Purpose Filename is a string of characters that make up a valid filename for the operating system. Returns NULL. “w+” Serches file.writing to a file. “w” Searches file. we must specify certain things about the file. “a” Searches file. its contents are overwritten.data store prog. Operation possible . Therefore.reading from the file.c text. all files should be declared as type FILE before they are used.NULL. If the file exists. a new file is created. Examples: input. Returns NULL. FILE is a defined data type. loads it into memory and sets up a pointer which points to the first character in it. if unable to open file. 62 . Data structure 3.appending new contents at the end of file. If the file doesn’t exist. If the file doesn’t exists a new file is created. its contents are destroyed. Filename 2. If the file doesn’t exist.reading existing contents. modifying existing contents of the file. if uanble to open file.reading existing contents. loads it into memory and sets up a pointer which points to the first character in it If file doesn’t exist it returns NULL. appending new contents to end of file. They include: 1. If the file doen’t exists. If the file exists.c student. if unable to open file. loads it into memory and sets up a pointerwhich points to the first character in it.writing new contents. a primary name and an optional period with the extension. Returns NULL. a new file is created. If the file exists. Operations possible . Cannot modify existing contents. reading them back and modifying existing contents of the file. Returns NULL. to the operating system. Operations possible .

. FILE *pt1. pt1 = fopen(“input”.. reading out of or writing to it is accomplished using the standard I/O routines.. *pt2. Note that both the filename and mode are specified as strings. This pointer which contains all the information about the file and it links between the system and the program.... fclose(pt1). we must specify what we want to do with the file.. . pt2 = fopen(“ouput”.. .. “w”). The file data is opend for reading and results is opend for writing. Consider the following statements: FILE *pt1... This ensures that all outstanding information associated with thefile is flushed out from the buffers and all links to the file are broken. “w”). The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. char s[80].. They should be enclosed in double quotaton marks. its contents are deleted and the file is opened as a new file.h> main() { FILE *fp.. fp = fopen(“filename”. “r”). If data file does not exit. fclose(pt2).. pt1 = fopen(“data”.. fp = fopen(“neha.. Mode can be one of the following: “r” opens the file for readng only “w” open the file for writing only “a “ open the file for appending (or adding) data to it. Once a file is closed.When we open a file. This program opens two files and closes them after all operations onthem are completed. “r”). In case.. *pt2. pt2 = fopen(“results”.. we may write data to the file or read the already existing data... The second statement also specifies the purpose of opening this file. “w”). Look at the following segment of a program to close the opend files.. INPUT/OUTPUT OPERATIONS ON FILES Once a file is opend...For example.. Following is the general format for declaring and opening a file: FILE *fp. #include <stdio. if(fp == NULL) 63 . the results file already exits. an error will occur.txt”. . “mode”). CLOSING A FILE A file must be closed as soon as all operations on it have been completed. To creat a new file: In this program we can write strings to a file using the function fputs(). its file pointer can be reused for another file. The first statement declares the variable fp as a “pointer to the data type FILE”.. The mode does this job.

exit().h> main() { FILE *fs. } while(1) { c = fgetc(fs). exit(). 64 . if(fs == NULL) { puts(“Cannot open source file”).c”. while(strlen(gets(s)) > 0) { fputs(s. } Note that each string is terminated by hitting enter. fs = fopen(“pr1. *ft. To terminate the execution of the program. Since fputs() does not automatically add a newline character to the end of the string. fp). exit().c”. printf(“Press two times Enter key to close the file\n”). }f close(fp). To copy the contents of a file into another file: In this program we can copy the contents of one text file into another text file. else fputc(c. printf(“Press Enter key at the end of the line\n”). }f t = fopen(“pr2. hit enter at the beginning of a line. we must do this explicitly to make it easier to read the string back from the file. if(c == EOF). fputs(“\n”. the fputs() function then writes the contents of the array to the disk. fclose(fs). break. fp). } printf(“\nEnter a few lines of text:\n”). Explanation: We have set up a character array to receive the string. which the program recognises as the signal to close the file and exit.{ puts(“Cannot open file”). This creates a string of zero length. character by character. #include <stdio. “r”). “w”). ft). }f close(fs). if(ft == NULL) { puts(“Cannot open targer file”). char c.

exit(). fp = fopen(“suhail. s). in which case fgets() returns a NULL. is the pointer to the structure FILE. 79. fp) != NULL) printf(“%s”. we attempt to read one more line. clrscr(). } Explanation: In the above program fgetc() function is used to reads characters from a file and fputc() function is used to write characters to a file. and the second is the maximum length of the string. getch(). if(fp == NULL) { puts(“Cannot open file”). “w”). The ft and fs are pointers for target file and source file. &bs). fclose(fp). strings. } while(fgets(s.txt”. Formatted Disk I/O Functions: For formatted reading and writing of characters. The fclose() is used to close the file. char s[80]. int age. When all the lines from the file have been read. floats. integers. } while(another == ‘Y’) { printf(“\nEnter name. char another = ‘Y’. fp = fopen(“employee. } Explanation: The function fgets() takes three arguments. scanf(“%s %d %f”. if(fp == NULL) { puts(“Cannot open file”).h> main() { FILE *fp.h> main() { FILE *fp. This third argument. It clears any characters remaining in the buffers. age and basic salary\n”). #include <stdio. clrscr(). as usual.fclose(ft). To read strings from the file and displays them on screen: #include <stdio. “r”). name. 65 . exit(). &age. float bs. The first is the address where the string is stored. This argument prevents fgets() from reading in too long a string and overflowing the array. char name[40].dat”. fscanf() and fprintf(). there exists two functions.

float bs.fprintf(fp. As in printf(). except that a FILE pointer is included as the first argument.dat”. The reason is to get rid of a pecularity of scanf(). another = getche(). fp = fopen(“employee. } Explanation: This program uses the fscanf() function to read the data from the disk. age. by using fprintf(). &bs) != EOF) printf(“\n%s %d %f”. getch(). &age. After supplying data for one employee. exit(). we can format the data in a variety of ways. “%s %d %f”. char name[40]. “r”). Here we use ‘stdin’. printf(“Another employee(Y/N)”). It is designed to remove or ‘flush out’ any data remaining in the buffer. getch(). as with fprintf(). which means buffer related with standard input device the keyboard. This function is similar to scanf(). } while(fscanf(fp.h> main() { FILE *fp. a pointer to FILE is included as the first argument. “%s %d %f\n”. In fact all the format conventions of printf() function work with fprintf() as well. which writes the values of three variables to the file. age and salary to appropriate variables and keeps the enter key unread in the keyboard buffer. name. fclose(fp). This function is similar to printf(). if(fp == NULL) { puts(“Cannot open file”). name. char another = ‘Y’.h> main() { FILE *fp. 66 . name. int age. we would hit the enter key. fflush(stdin). age. To avoid this problem we use the function fflush(). To read formatted file and displays them on screen: #include <stdio. bs). except that. What scanf() does is it assign name. To write records to a file using structure: #include <stdio. The argument to fflush() must be the buffer which we want to flush out. So when it’s time to supply Y or N for the question ‘Another employee (Y/N)’ getche() will read the enter key from the buffer thinking that user has entered the enter key. bs). clrscr(). We have used fflush() function. }f close(fp). } Explanation: The key to this program is the function fprintf().

name. e. e.struct emp { char name[40]. }. } Note: In this format numbers would occupy more number of bytes. scanf(“%s %d %f”. “r”).bs) != EOF) printf(“\n%s %d %.age. another = getche(). &e.name. fprintf(fp.age. } while(another == ‘Y’) { printf(“\nEnter name. struct emp { char name[40]. &e. e. exit(). since the file is opend in text mode.age.bs). e.name. struct emp e. &e. “%s %d %. age and basic salary:”). getch(). float bs. fflush(stdin). }f close(fp). fclose(fp).bs).bs). To read records from a file using structure: #include <stdio.age. &e. if(fp == NULL) { puts(“Cannot open file”). } while(fscanf(fp. getch().dat”. }. printf(“Add another record (Y/N)”). “w”). fp = fopen(“employee. e.2f\n”. float bs. “%s %d %f”. e. e. int age.name. } The getw and putw Functions: 67 . if(fp == NULL) { puts(“Cannot open file”). exits(). struct emp e.dat”.2f”. fp = fopen(“employee. e.h> main() { FILE *fp. int age.

“w”). i <= 30. “r”).The getw and putw are integer-oriented functions. i. “r”). for(i = 1. } ERROR HANDLING DURING I/O OPERATIONS 68 . printf(“\n\nContents of even file\n\n”). putw(integer. printf(“Contents of data file\n\n”). while( (number = getw(f1) ) != EOF) { if(number %2 == 0) putw(number. fp). Code a program to read these numbers and then write all odd numbers to a file to be called odd and all even numbers to a file to be called even. &number). The general forms of getw and putw are: getw(fp). “r”). f3 = fopen(“even”. *f2. f2 = fopen(“odd”. while( (number = getw(f2) ) != EOF) printf(“%4d”. f3 = fopen(“even”. *f3. putw(number. printf(“\n\nContents of odd file\n\n”). “w”). if(number == -1) break. i++) { scanf(“%d”. f1 = fopen(“data”. f2 = fopen(“odd”. #include <stdio. f1). while( (number = getw(f3) != EOF) printf(“%4d”. They are similar to the getc and putc functions and are used to read and write integer values. }f close(f1). fclose(f3). f3). In this programwe use three files simultaneously and therefore we need to define three file pointers f1. number).h> main() { FILE *f1. int number. These functions would be useful when we deal with only integer data. Example: A file named data contains a series of integer numbers. } fclose(f1). else putw(number. f1 = fopen(“data”. number). fclose(f2). f2). fclose(f2). fclose(f3). f2 and f3. “w”).

and so on. There are occations. offset is a number or variable of type long. without having to close and open the file. The position can take one of the following three values: Value 0 1 2 69 Meaning Beginning of file Current position End of file . the statement rewind(fp). This function helps us in reading a file more than once. second as 1. and position is an integer number. Remember that whenever a file is opened for reading or writing.It is possible that an error may occur during I/O operations on a file. file ptr is a pointer to the file concerned. This means that n bytes have already been read (or written). 3. would assign 0 to n because the file position has been set to the start of the file by rewind. This can be achieved with the help of the functions fseek. RANDOM ACCESS TO FILES We have discussed file functions that are useful for reading and writing data sequentially. the first byte in the file is numbered as 0. a rewind is done implicity. n would give the relative offset (in bytes) of the current position. that corresponds to the current position. Trying to use a file that has not been opened. Trying to perform an operation on a file. and rewind available in the I/O library. It takes the following form: fseek(file ptr. position). 2. rewind takes a file pointer and resets the position to the start of the file. when we are interested in accessing only a particular part of a file and not in reading the other parts. which can be used later in the program. Typical error situations include: 1. This function is useful in saving thecurrent position of a file. Opening a file with an invalid filename. fseek function is used to move the file position to a desired location within the file. 5. offset. when the file is opened for another type of operation. Trying to read beyond the end-of-file mark. Device overflow. ftell. n = ftell(fp). For example. however. 4. 6. ftell takes a file pointer and returns a number of type long. The offset specifies the number of positions (bytes) to be moved from the location specified by position. Attempting to write to a write-protected file. Rememer. It takes the following form: n = ftell(fp).