You are on page 1of 65

A Brief History of the C Language

You might be wondering about the origin of the C language and where it got its name. C
was created by Dennis Ritchie at the Bell Telephone Laboratories in 1972. The
language wasn’t created for the fun of it, but for a specific purpose: to design the UNIX
operating system (which is used on many computers).

Because C is such a powerful and flexible language, its use quickly spread beyond Bell
Labs. Programmers everywhere began using it to write all sorts of programs. Soon,
however, different organizations began utilizing their own versions of C. In response to
this problem, the American National Standards Institute (ANSI) formed a committee in
1983 to establish a standard definition of C, which became known as ANSI Standard C.
With few exceptions, every modern C compiler has the ability to adhere to this standard.

Now, what about the name? The C language is so named because its predecessor was
called B. The B language was developed by Ken Thompson of Bell Labs.

General characteristics of C

C is a middle level language. Its characteristics lie between those of problem oriented
language such as FORTRAN, Basic, Pascal and low level Languages. It is a procedural
language. It is reliable, efficient, simple and easy to understand. The approach of
programming in C is bottom-up. The modularity feature of C language, i.e. breaking the
problem into modules called the function makes it easier to organize and maintain.


You should take certain steps when you’re solving a problem. First, you must define the
problem. If you don’t know what the problem is, you can’t find a solution! Once you
know what the problem is, you can devise a plan to fix it. Once you have a plan, you can
usually implement it. Once the plan is implemented, you must test the results to see
whether the problem is solved. This same logic can be applied to many other areas,
including programming.

When creating a program in C (or for that matter, a computer program in any language),
you should follow a similar sequence of steps:

1. Determine the objective(s) of the program.
2. Determine the methods you want to use in writing the program.
3. Create the program to solve the problem.
4. Run the program to see the results.

Data types and its information
Integer types—these are whole numbers without any decimal portion. They can be
signed or unsigned. They are also classified as short and long integers depending on their
Floating point types—these are real numbers (with decimal portion) which are stored in
32 bits with 6 digits of precision. There are two types of such numbers in C. These are
float and double. The data type double offers more precision when compared to float data
Character type—A single character is defined as a char data type. They are stored in one
byte of internal storage. They can be signed or unsigned. Signed char can have values
between 0 and 255 while unsigned have –128 to 127 ranges.

User defined data types—Apart from the above, the programmers can define their own
data types using the typedef keyword.

Fundamental Type Derived Types Description Minimum Range
Char Signed char Mininum of 8 bits 0 to 127
Unsigned char -128 to 127
0 to 255
Int Signed Mininum of 16 bits -32,768 to 32,767
Signed int same
(default) same
unsigned same
unsigned int 0 to 65,535
0 to 65,535
Short Signed short Mininum of 16 bits -32,767 to 32,767
Short int same
Signed short int same
Unsigned short same
Unsigned short int 0 to 65,535
0 to 65,535

Long Signed long Mininum of 32 bits -2,147,483,648 to
Long int 2,147,483,647
Signed long int same
Unsigned long same
Unsigned long int same
0 to 4,294,967,295
Enum Mininum of 16 bit int -32,768 to 32,767
Float Mininum of 6 decimal
Digit precision -1038 to +10 -38
,0, 1038 to +10 -38

Double long double Minimum of 10 decimal -1038 to +10 -38
Digits precision ,0, 1038 to +10 -38

Void Always incomplete No value, no storage


A Computer is an Electronic Device which takes the given input and gives the required
output. A Computer requires a means of accepting data, somewhere to store the sequence
of operations to require and finally a way of communicating the results. These facilities
are common to any computer regardless of the task.

Compute means to calculate or determine something by mathematical means. The most
commonly used Computer, consists of three parts
• Input Devices (Key-board)
• Central Processing Unit (C.P.U)
• Output Devices (Monitor)
Further a C.P.U is divided into three main parts
1. Arithmetic and Logical Unit (A.L.U)
2. Control Unit (C.U)
3. Memory Unit (M.U)


Input Output
Device Control Device


Figure: Block Diagram of Computer.

Program: Set of instructions given to a computer to get the required output is called a
program. For writing a program we have four steps
1. designing the problem
2. designing an algorithm
3. coding and testing
4. maintenance

an algorithm is always a language- free computational steps. Thus “It is a sequence of steps which transforms an input into an output/ Step by Step representation of a program is called as “Algorithm”. Program to find sum of two numbers Algorithm: Step 1: Start Step 2: Take the input “a. Step 1: Input A.b” Step 3: Take the operators “+. The time and space used by the algorithm are the two main measures for the efficiency of the algorithm The Process to Write the Algorithm is given below. Suppose an algorithm has m input data. A single problem may have multiple algorithms. B. X2 Else if D = 0 then: (a)Set X = -B / 2 * A (b)Print X Else: Print “Roots are imaginary” End If Step 4: Exit The fundamental knowledge necessary to solve problems using a computer is the notation of a Algorithm.SQRT(D))/ 2 * A (c) Print X1.Algorithm: Algorithm can be defined as a well-defined computational procedure that takes single value or a set of values as inputs and produces a single or multiple values as output. .=” Step 4: Take the results into “c” Step 5: Process the problem “c=a+b” Step 6: Assign the output to “c” Step 7: Stop Algorithm to find the roots of quadratic equation for all the cases. Also. C Step 2: Set D = B * B – 4 * A * C Step 3: If D > 0 then : (a)Set X1 = (-B + SQRT(D))/ 2 * A (b)Set X2 = (-B . In order to compare algorithms. we must have some criteria to measure the efficiency of our algorithms.

In this standard convention • Parallelogram is used to represent to Input and Output operations.Flow charts: Pictorial/Diagrammatical representation of an algorithm is called Flow Charts. • Circle is used to join different parts of a Flowchart. • Rectangles are used to indicate processing the operation. are used to indicate beginning (Start) or End (Stop) points. Parallogra Start/sto m p circl rectangle e decisio n Flowchart for Sum of two given numbers: . • Diamond shaped is used for Decision making (yes/no). such as storage and arithmetic. • Flowlines/Arrows are used to indicate the direction to be followed in a Flowchart. • Oval/rectangle with Rounded ends. For easy visual recognition a standard convention is used in drawing flowchart. this is called as a connecter.

b. start Take the variables a.c Read the variables a.b Compute c=a+b Print the value of c stop The structure of a C program is .

constant. • The printf() statement is a library function that displays information on-screen. Therefore a complete C program would comprise of a series of statements • Blank spaces may be inserted between two words to improve the readability of the statement. Thus semi-colon acts as a statement terminator. there are number of directives and in that directives we have the Key-word and statements. .. All statements that belong to main() are enclosed within a pair of braces{ }. The return statement returns a value of 0 to the operating system just before the program ends. return type. getch etc. it executes the program statements. However. • Pre-processor directive are that which acts as Foundation for the program. and the meaning is it doesn’t return any written type/value. In other words. no blank spaces are allowed within a variable.). Comment lines Preprocessor directive statements Global variables void main ( ) { Data type declaration with variable. or keyword. • The scanf() statement is another library function. The printf() statement can display a simple text message or a message and the value of one or more program variables. STDIO—Standard Input and Output In this Directive we have printf. • Every C statement must end with a semi-colon (. } • Each instruction in a C program is written as a separate statement.e. And this is called as Function and acts as a starting point of the program. • We can include comment lines i. • All statements are entered in small case letters. ……. either we can use single line or multi line comments for the user convenient also. It reads data from the keyboard and assigns that data to one or more program variables. • The return statement is that. it calculates the product of the variables x and y and returns the result to the program statement that called function. • Void means a keyword. CONIO—Console Input and Output In this Directive we have clrscr. Statements. scanf etc. • Main() is a collective name given to a set of statements.

C. 6. . 3. Use the keys ALT+F9 to compile the program (to check if any errors present in the program). Type the complete program. The compiler (TC. • Input statements: the statements for storing and reading the values Ex:scanf( ) Output statements: the statements which are used to give required outputs Ex: printf( ) How to Get into C Compiler: Assuming that we are using a Turbo C or Turbo C++ compiler. under a proper name(say add.c). Use the keys CTRL+F9 to run the program(to get the output of the program) 7. Start the compiler at C> prompt. 5. 4. Select New form the File menu. 2.EXE is usually present in C:\TC\BIN directory). here are the steps that we need to follow to compile and execute our C program… 1. Save the program using F2/go the File menu select the Save option. ADDITION. Use ALT+F5 also to view the output.

b. &a). b. c). */ 2: #include <stdio. 11: 12: /* Input the second number */ 13: printf("Enter another number: "). 10: scanf("%d". 15: 16: /* Calculate and display the product */ 17: c = a+b.c. &b). 18: printf ("a=%d b=%d c= %d\n".h> 3: #include <conio. 21: } Enter a number: 5 Enter another nunber: 3 a=5 b=3 c= 8 Alphabetic escape sequences representing nongraphic characters in the execution character set are intended to produce actions on display devices as follows: . 19: 20: getch().1: /* Program to calculate the Addition of two numbers. a.h> 4: void main() 5:{ 6: int a. 7: clrscr(). 8: /* Input the first number */ 9: printf("Enter a number : "). 14: scanf("%d".

the behavior is unspecified. Execution Meanings characters \a (alert) Produces an audible or visible alert. If the active position is at or past the last defined horizontal tabulation position. If the active position is at or past the last defined vertical tabulation position. the behavior is unspecified. \f ( form feed) Moves the active position to the initial position at the start of the next logical page. If the active position is at the initial position of a line. \b (backspace) Moves the active position to the previous position on the current line. the behavior is unspecified. \n (new line) Moves the active position to the initial position of the next line. The active position shall not be changed. OPERATORS AND EXPRESSIONS . \r (carriage return) Moves the active position to the initial position of the current line. \v (vertical tab) Moves the active position to the initial position of the next vertical tabulation position. \t (horizontal tab) Moves the active position to the next horizontal tabulation position on the current line. The active position shall not be changed.Produces an audible or visible alert.

For Example: If the variable I and j have been declared by the statement. int i.e. in general is a symbol that operates on a certain datatypes. Each of these . double and long double) numbers. then a valid expression involving the assignment operator would be as follows: int i. 2.For example. Assignment operators. Arithmetic operators.. Logical operators. the operator + is the addition operation. Increment and Decrement operators. Arithmetic Operators: The Arithmetic Operators perform arithmetic operations and can be classified into Unary and Binary arithmetic operators.j. We often compare two similar quantities and depending on their relation. logical and character expressions. 8. In C.j=5. A list of arithmetic operators and their meaning are given below: Operators Meaning + Addition or unary plus . The arithmetic operators can operate on any built in data type. Types of Operators: In C. 7. every expression results in some value of a creation type that can be assigned to a variable. It can operate on integer. relational operators are used to compare arithmetic. constants and operators written according to the syntax of the language. 9. 3. 4. character and real (float. 6. Bitwise operators. every expression evaluates to a value i. we take some decisions. Relational operators. An expression is a combination of variables. A list of operator types is given below: 1. Conditional operators. Comma operators. 5.An operator. These comparisons can be done with the help of relational operators. operators can be classified into various categories based on their utility and action. Subtraction or unary minus * Multiplication / Division % Modulo division(remainder after division) Relational Operators: While arithmetic operators are used to evaluate arithmetic expressions. Other operators.

The whole expression involving the relational operator then evaluates to an integer. Clearly false && anything is always false. They evaluate their left hand operand. Not operates on a single logical value. Logical operators The Logical Operators is used to compare or evaluate logical and relational expressions. These are the usual And. its effect is to reverse its state. if(i= =j) printf(“hi”). and one (1) if the condition is true. Operator Meaning && Logical AND || Logical OR ! Logical NOT They are frequently used to combine relational operators. Here is an example of its use. Increment/Decrement . then we use the relational operators. Or and Not operators. if ( ! acceptable ) printf("Not Acceptable !!\n"). Eg. and then only evaluate the right hand one if this is required. For Example: x < 20 && x >= 10 In C these logical connectives employ a technique known as lazy evaluation. In such cases the second test is not evaluated. There are three logical operators in C language.. Operator Meaning < Less than > Greater than <= Less than or equal to >= Greater than equal to == Equal to != Not equal to For Example: if we want to compare to variable.operators compares their left hand side with their right hand side. It evaluates to zero if the condition is false. true || anything is always true.

If the expression 1 is true then expression 2 is evaluated and this becomes the value of . i). the operator follows the operand (e. ++ i) then the operand will be altered in value before it is utilized for its intended purpose within the program. Suppose i is an integer variable that has been assigned a value of 5. The expression + +i. depending on whether the operator is written before or after the operand. If however. printf ( i = %d\n”.g. i++). ++i). i). printf (“ i = %d\n”. The operand used with each of these operators must be a single variable. E. printf (“ i = % d\n”.The increment operator (++) causes its operand to be increased by one where as the decrement operator causes its operand to be decreased by one. whereas the decrement operator causes the value to be decreased by 1 so. expression 1? expression 2: expression 3 When evaluating a conditional expression.g.g. i). i ). There printf statements will generate following three lines of out put i=1 i=2 i =2 Now let us take the second case printf (“ i = %d\n”. printf (“ i = %d\n”.g. now the new variable of i will be 4 i ++ means i = i + 1 — i means i = i-1 The increment and decrement operators can each be utilized in two different ways. The statement will generate the following three lines of output i=1 i=1 i=2 Conditional Operators Conditional operator is (?:) A expression that makes use of the conditional operator is called a conditional expression for e. printf (“ i = %d\n”. expression 1 is evaluated first.g i ++) then the value of the operand will be altered after it is utilized e. causes the value of i to be increased by one. If the operator precedes the operand (e.

There is usually no trouble in assigning a value to a variable of different type. Type conversion You can mix the types of values in your arithmetic expressions. if expression 1 is false then expression 3 is evaluated and this becomes the value of the conditional expression e. and the resulting value is assigned to variable. The conditional expression is (f < g)? f: g It takes the value f if f is less than g otherwise the conditional expression takes on the value of g. the right side can be any expression. The value will be preserved as expected except where. Its use in programming is somewhat different from its use in regular math. Where integer and real types meet. in a C program. it means "assign the value of y to x. The solution is to use a method called casting which temporarily disguises a value as a different type. the form is as follows: variable = expression. it doesn’t mean "x is equal to y. the result will usually be of the larger size. eg. This can lead to corrupt results. • The variable is too small to hold the value. . Otherwise where types of different size are involved. the result will be a double. Assignment Operators The assignment operator is the equal sign (=). The function has no way of determining the type passed to it. and the left side must be a variable name. This is often done deliberately by the programmer. When executed. The value is rounded down. so a float and a double would produce a double result. • The variable is an integer type and is being assigned a real value. In the conditional expression shown below suppose f and g are floating point variables.g. so automatic conversion cannot take place. In other words conditional expression returns the value of the smaller of the two variables.conditional expression However. expression is evaluated." In a C assignment statement. The function sqrt finds the square root of a double. If you write x = y." Instead. char types will be treated as int. Thus. In this case it will be corrupted (this is bad). Values passed as function arguments must be of the correct type.

int i = 256. root = sqrt( (double) i). OPERATOR PRECEDENCE AND PARENTHESES . The cast is made by putting the bracketed name of the required type just before the value. int root. is also a double. (double) in this example. The result of sqrt( (double) i). but this is automatically converted to an int on assignment to root.

When an expression is evaluated. what is the order in which operations are performed? The importance of this question is illustrated by the following assignment statement: x = 4 + 5 * 3. assigns the value 19 to x because the multiplication is performed before the addition. and modulus · Addition and subtraction If an expression contains more than one operator with the same precedence level. what if you wanted to add 4 to 5 and then multiply the sum by 3? C uses parentheses to modify the evaluation order. so it is performed first: 12 % 5 * 2 The expression evaluates to 4 (12 % 5 evaluates to 2. without regard to operator precedence. Returning to the previous example. Performing the addition first results in the following. Clearly. . division. some rules are needed about the order in which operations are performed. you could write x = (4 + 5) * 3. evaluation proceeds from the innermost expression outward. · Unary increment and decrement · Multiplication. What if the order of precedence doesn’t evaluate your expression as needed? Using the previous example. in the following expression. the % and * have the same precedence level. operators with higher precedence are performed first. In contrast. and x is assigned the value 19: x = 4 + 15. A subexpression enclosed in parentheses is evaluated first.In an expression that contains more than one operator.(2 * (10 + (8 / 2))). This order. the operators are performed in left-to-right order as they appear in the expression. but the % is the leftmost operator. you see that the statement x = 4 + 5 * 3. When parentheses are nested. The expression 4 + 5 inside parentheses is evaluated first. Look at the following complex expression: x = 25 . Each operator has a specific precedence. called operator precedence. is strictly spelled out in C. 2 times 2 is 4). You can use multiple and nested parentheses in an expression. and x is assigned the value 27: x = 9 * 3. For example. you have the following. if the multiplication is performed first. so the value assigned to x is 27. Thus.

is evaluated. Look at this expression: w*x/y+z/y Because of precedence. and the result of the division is then multiplied by z. As was mentioned in the previous section. The last. is evaluated. the result of the multiplication is then divided by y. yielding the value 28: 25 . The decision control structure in C can be implemented in C using . the multiplication and division are performed before the addition. or the compiler generates an error message.28. Across precedence levels.(2 * 14) 3. Moving outward. Look at another example: w * x / ++y + z / y If the left subexpression is evaluated first. yielding the value 4: 25 . Near the end of this unit. is evaluated.28 4. For example. even when they aren’t needed for modifying operator precedence.(2 * (10 + 4)) 2. 8 / 2. there is no guarantee of left-to-right order. they are evaluated left to right. assigning the value -3 to the variable x: x = -3 You might want to use parentheses in some expressions for the sake of clarity. y isn’t incremented. the section "Operator Precedence Revisited" lists the precedence of all of C’s operators. if C expressions contain more than one operator with the same precedence level. The innermost expression. y is incremented when the second expression is evaluated. in the expression w*x/y*z w is multiplied by x. or outermost. however. 2 * 14. 25 . If the right expression is evaluated first. and the result is different.The evaluation of this expression proceeds as follows: 1. It might not be clear to you why this matters. 10 + 4. expression. yielding the value 14: 25 . C doesn’t specify whether the subexpression w * x / y is to be evaluated before or after z / y. the next expression. Parentheses must always be in pairs. you should avoid this sort of indeterminate expression in your programming. The final expression. is evaluated first. Therefore. However.

For the if expression there is no semi-colon. whatever it is true. scanf(“%d”. } Here the keyword if tells the compiler that what follows. It the condition is not true then the statement is not executed instead the program skips past it. If the condition. It does nothing when the condition is false. /* FIND WHETHER THE GIVEN NUMBER IS LESS THAN OR EQUAL TO 10 */ main( ) { int num. It the . printf(“Enter a number less than 10”). then the statement is executed. } } If – else Syntax: if (this condition is true) { execute this statement. is a decision control instruction. if(num < = 10) { printf(“The number is less than 10”). & num). } The if statement by itself will execute a single statement or a group of statements when the condition following if is true. } else { execute the statements. which are either true or false. The relational operators help us to build expression. The condition following the keyword if is always enclosed within a pair of parentheses. The condition in C is evaluated using C’s relational operators.The if statements • If-else statement • Multiple statements • Nested if statement • Nested if-else statement The if Statement The general form of if statement looks like this: Syntax: if (this condition is true) { execute this statement.

} else { hra = 500. } The Loop Control structure . printf(“Enter basic salary”). } gs = bs+hra+da.else construct within the body of the if statement or the body of an else statement.condition is false then a group of statements can be executed using else statement. da = bs * 90/100. gs. if(bs <1500) { hra = bs * 10/100. else { do this. scanf(“%f”. Syntax: if(condition) { if (condition) do this. This is called ‘nesting’ of ifs. and this. da = bs * 98/100. } } else { do this. da. The following program illustrates this /* CALCULATION OF GROSS SALARY */ main( ) { float bs. } Nested if – else If we write an entire if . hra. printf(“gross salary = Rs. %f”. & bs). gs).

& n. count = count +1. } while (this condition is true). There is a minor difference between the working of while and do-while loops. count = 1. The difference is the place where the condition is tested. } } The do-while Loop The do-while loop takes the following form Syntax: do { statements. & p.. & r). (a) Using a while statement (b) Using a do-while statement (c) Using a for statement The while Loop The general from of while is as shown below: Syntax: initialise loop counter. n. si. } The parentheses after the while contains a condition so long as this condition remains true all statements within the body of the while loop keep getting executed repeatedly /* CALCULATION OF SIMPLE INTERSET FOR p. while(count < = 3 ) { printf(“\n Enter values of p.n. The while tests the condition before .. r */ main( ) { int p. scanf(“%d %d %f”. float r. count. They are as follows. while (test loop counter using a condition) { statements. si = p*n*r/100. increment loop counter.These are three methods by way of which we can repeat a part of a program. …. ……. printf(“simple interest = Rs. %f”. si). n and r”).

executing any of the statements within the while loop. printf(“Simple interest = Rs %f \n”. scanf(“%d %d %f”. The for Loop The general form of for statement is as under: Syntax: for( initialise counter. As against this the do-while tests the condition after having executed the statements within the loop. test counter. si). } while (5<1). float r.n and r */ main( ) { int p. count = count +1) { printf(“Enter values of p. since first the body of the loop is executed and then the condition is tested. for(count = 1. increment counter) { statements.: main( ) { while(5<1) printf(“Hello \n”). the printf will not get executed at all since the condition fails at the first time itself.q. } In the above program the printf( ) would be executed once. si. & r). & p.n. } } The break Statement . si = p * n * r / 100. count <=3. ……. count.n and r”). } In the above e.g. E. & n. Now let’s now write the same program using a do-while loop. } Now let us write the simple interest problem using the for loop /* CALCULATION OF SIMPLE INTERST FOR p. main( ) { do { printf (“Hello \n”).

} The continue Statement The keyword continue allows us to take the control to the beginning of the loop bypassing the statements inside the loop which have not yet been executed.The keyword break allows us to jump out of a loop instantly without waiting to get back to the conditional test. i. the number is not a prime. for(i = 1. e. i++) { for(j=1.g. When the keyword continue is encountered inside any C loop. The following program is to determine whether a number is prime or not. } i++ } if(i = = num) printf(“Prime number”). j++) { if (i= =j) . When the keyword break is encountered inside any C loop. If the remainder of any of the divisions is zero. control automatically passes to the beginning of the loop.To test a number is prime or not. i< = 2. scanf(“%d”.j.q. Logic:. control automatically passes to the first statement after the loop. j<=2. i=2 while (i < = num -1) { if (num%i= = 0) { printf(“Not a prime number”). break. following program implements this logic main( ) { int num. divide it successively by all numbers from 2 to one less than itself. for e. printf(“Enter a number”). &num). main( ) { int i.

default: statements. The selection is based upon the current value of an expression that is included within the switch statement.continue. printf(“\n%d%d\n”. The form of switch statement is.j). } ARRAYS . the continue statement takes the control to the for loop (inner) bypassing rest of the statements pending execution in the for loop(inner). } } The output of the above program would be. The Case Control structure switch Statement:- The switch statement causes a particular group of statements to be chosen from several available groups. Syntax: switch (integer expression) { case constant 1: statements. break.. case constant 3: statements. break. i. break... 12 21 when the value of i equal to that of j. case constant 2: statements.

Ex: consider an array name salary which represent a set of salaries of a group of employees . . number[1]=40. number[3]=57. and the computer reserves five storage locations as shown below: number[0] number[1] number[2] number[3] number[4] The values to the array elements can be assigned as follows: number[0]=35. This would cause the array number to store the values as shown 35 40 20 57 19 number[0] number[1] number[2] number[3] number[4] The subscript of an array can be integer constants or variables.. salary[10] denotes salary of 10th employee. number[4]=19.char and the size indicates the maximum number of elements that can be stored inside the array. the individual values are called elements. The type specifies the type of element that will be contained in the array such as float . Arrays can be of any variable type. 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-subscripted variable or a one-dimensional array.e. Array name subscript(index) Index : A particular value is indicated by writing a number called Index number of subscript in brackets after the array name. int number[5]. i. number[2]=20. Declaration: type variable-name[size]. float f[12]. Ex: datatype arrayname[size]. Ex: int a[10]. While the complete set of values is referred as an array .int .INTRODUCTION: An array is a group of related data items that share a common name.

color[0]=’R’ color[1]=’E’ color[2]=’D’ The elements of second array are . -----this declares name as a character array(string) variable that can hold a maximum of 10 characters. char color[]=”RED”. Initializing a character array: char color[3]=”RED”. The array definition could also have been written as char color[4]=”RED”. The elements of first array are . Ex:The string ”WELL DONE” is stored as follows ‘W’ ‘E’ ‘L’ ‘L’ ‘‘ ‘D’ ‘O’ ‘N’ ‘E’ ‘\0’ When the compiler sees a character string .it terminates it with an additional null character . char name[10].When declaring character arrays we must always allow one extra element space for the null terminator. color[0]=’R’ color[1]=’E’ color[2]=’D’ color[3]=’\0’ Second type of initialization correct. Sorting Techniques: .Thus the element name[9] holds the null character ‘\0’ at the end.

is considered to be a very faster method to sort the elements. Also. Let us understand this with a simple example. (1) We will take 74 as the pivot and move it to position so that the new list becomes – 39. 84 3 32. 39. these elements (39. Now. we get 84. Reapply the process on the partition. 74. In this method. . This procedure is repeated till the entire array is sorted. 97.39. 74. 32. The partition to the left is 35. 35. Consider the list—74. 39. Thus. 35. This process proceeds till we get the sorted list of elements. 84. 84.Selection sort Bubble sort. Following is the table. the first element of the list is selected. i. 35. we get 32. 74. 97. invented by Hoare. 84. 84. (2) Now take the partitioned list—39. 32. If any element is found to be lesser than the selected element.e. which are right to the pivot. the elements 97 and 84. 39. 39. 32. 32. which gives the status of the list after each pass is completed. we have 32. 84 4 32. 35. the first element is considered to be the pivot element. 97 Quick sort This method. 35. 32. Taking 97 as the pivot and positioning it. (3) Apply the process to the right partition of 74 which is 97. The elements to the left of the pivot are less than the pivot while the elements to the right of the pivot are greater than the pivot. The method is also called partition exchange sorting. Selection sort: As the name suggests.. 97. 97. 35. the list is divided into two based on an element called the pivot element. The method is based on divide-and-conquer technique. Let us take 39 as the pivot. 35. 35 and 32) are yet to be sorted. move the pivot element into its correct position in the list. 39. Usually. 97. Insertion sort. 84 2 32. 35. the entire list is divided into various partitions and sorting is again and again applied on the partitions. 32. 39. 84 5 32. Pass List after pass 1 32. 84. 74. 74. 35. 35. Consider the list 74. these two are swapped. There is no right partition. Moving it to the correct position gives—35. 97. The process is reapplied to each of these partitions. Similarly. 74. 39. are yet to be sorted. Let us understand this by an example. Note that the elements to the left are lesser than 74. 97. 35. It is compared repeatedly with all the elements. 97. 39.

int left. printf(“\nArray after sorting:\n”). } void sort(int elements[]. int maxsize) { sort(elements. void sort(int elements[]. elements[i]). i++) printf(“[%i]. r = right.1). } void quickSort(int elements[]. i < maxsize. “. maxsize . quickSort(elements. i < maxsize. printf (“\n”). int elements[MAXSIZE]. l = left. int left. while (left < right) { while ((elements[right] >= pivot) && (left < right)) . Let us assume that an array named elements[] will hold the array to be sorted and maxsize is the number of elements to be sorted. l. #include <stdlib. i++) printf(“[%i]. scanf(“%d”. for (i = 0.&maxsize). pivot = elements[left].h> #define MAXSIZE 500 void quickSort(int elements[]. for (i = 0. maxsize. 0.i).(4) Assembling all the elements from each partition. maxsize). int right) { int pivot.elements[i]). r. we get the sorted list. “. C program for quick sort The quick sort is a very good example for recursive programming. int right). We will also assume that the sorting order is ascending in nature. } printf(“\nArray before sorting:\n”). printf(“\nEnter the values one by one: “). int maxsize). for (i = 0.&elements[i]). printf(“\nHow many elements you want to sort: “).h> #include <stdio. i < maxsize. scanf(“%d”. int main() { int i. i++) { printf (“\nEnter element %i :”.

left++. } } elements[left] = pivot. If the first element is less than the second element. (1) Compare 74 and 39. 84. if (left != right) { elements[right] = elements[left]. pivot = left. However this is the most inefficient algorithm. If the first element is greater than the second element. right—. 74. 97. 97. } while ((elements[left] <= pivot) && (left < right)) left++. (2) Compare 39 and 35. 39. 84.right—. if (left < pivot) sort(elements. 97. The procedure continues with the next two elements. goes and ends when all the elements are sorted. left. they are undisturbed. The method takes two elements at a time. It compares these two elements. Pass 1: (first element is compared with all other elements)—Note that the first element may change during the process. 39. Since 35 < 84. pivot + 1. they are undisturbed. 84. 84. Let us understand this method. 74. left = l. 35. 35. they are left undisturbed. 74. they are swapped. right = r. 74. 39. Since 74 > 39.1). if (left != right) { elements[left] = elements[right]. right). (3) Compare 35 and 97. 84. 39. then they are swapped. Since 35 < 97. pivot . The array is now 35. The array is now 35. . 97. Since 39 > 35. (4) Compare 35 and 84. if (right > pivot) sort(elements. 97. they are swapped. The array now changes like 35. } Bubble sort: The simplest and the oldest sorting technique is the bubble sort. The array now changes like 39. Consider the list 74.

(3) Compare 39 and 84. Since 39 < 84. replace the > symbol with < symbol in the comparison statement. The second pass begins with the second element and is compared with all other elements. 97.At the end of this pass. 84. 39. This pass also did not bring any change in the array elements. Pass 3: (fourth element is compared) (1) Compare 97 and 84. 39. Note that the last number is not compared with any more numbers. the array arr[] will be sorted in the ascending order. The next pass starts. The next pass starts. we have: Number of comparisons in the first pass = (n – 1) Number of comparisons in the second pass = (n – 2) Number of comparisons in the last pass = 1 Thus. The array is now 35. Since 74 < 97. Since 39 < 97. Since 39 < 74. The sorting ends here. 74. the total number of comparisons at the end of the algorithm would have been: (n – 1) + (n – 2) + … + 2 + 1 = n (n – 1) / 2 = n2 / 2 + O(n) = O(n2) Hence the order of the bubble sort algorithm is O(n2). they are undisturbed. At the end of the execution. Pass 3: (third element is compared) (1) Compare 74 and 97. Thus. Note that the number of comparisons will be reduced by one since the first element is not compared any more. You can see from the algorithm that each time (each pass). they are undisturbed. 74. 39. the first element will be in the correct place. (2) Compare 74 and 84. Since 97 > 84. The array is now 35. 39. The array is now 35. The array is now 35. The array is now 35. The array is now 35. 84. Efficiency of bubblesort Let us now analyze the efficiency of the bubble sort. 74. 84. 97. TWO-DIMENSIONAL ARRAY: . 84. 39. 97. (2) Compare 39 and 97. Pass 2: (second element is compared) (1) Compare 39 and 74. they are swapped. If you need to perform a descending order sorting. 39. 84. This pass did not bring any change in the array elements. they are undisturbed. 74. 74. they are undisturbed. 97. 97. 84. Since 74 < 84. 74. 97. they are undisturbed. the number of elements scanned for comparison reduces by 1.

{1. When all the elements are to be initialized to zero .1.A list of items can be given one variable name using two subscripts and such a variable is called a two-dimensional array. The above statement can be equivalently written as int table[2][3]={{0. .1}).0.0}.1.0.1. the first index selects the row and second index selects the column within that row.0. {1.1. INITIALIZING TWO-DIMENSIONAL ARRAYS: int table[2][3]={0.0.0}. each dimension of the array is indexed form zero to its maximum size minus one.{0}}.{0}. in all the above statements initializes the elements of the first row to zero and the second row to one. Other way of initialization is.1} }.the following short-cut method may be used.1}. Ex: datatype arrayname[row_size][column_size]. int m[3][5]={{0}. or int table[2][3]={ {0. Two dimensional arrays are stored in memory as shown below: Column0 column1 column2 Row 0 [0][0] [0][1] [0][2] 310 275 100 Row 1 [1][0] [1][1] [1][2] 200 175 150 Row 2 [2][0] [2][1] [2][2] 30 75 15 Row 3 [3][0] [3][1] [3][2] 250 195 160 As with single dimensional arrays .

int table[2][2][2][4]. The square brackets may be empty . table[1][2]=1. table[0][1]=0. Multidimensional arrays: Arrays with more than two dimensions also can be defined. Type arrayname[s1][s2]…[sn]. declares a three dimensional array. table[0][0]=0. declares four dimensional array.since the array size will have been specified as a part of the array definition .these are called Multi dimensional arrays. table[1][0]=1. Initial values cannot be included in the declarations. 1. table[1][1]=1.Array declarations are customarily written in this form.the declaration is written in the same manner as the array definition with the following exceptions. 2. String handling functions . Ex: int a[3][3][3]. These rules apply to formal argument declarations within functions as well as external variable declarations. If a program requires a one-dimensional or multi-dimensional array declaration (because the array is defined elsewhere in the program) . table[0][2]=0.

source). } output 13 0 32 In the first printf statement we use the strcmp( ) function with string1 and string2 as it arguments. } output will be source : orange target : orange . getch( ). strcmp(string1. clrscr( ). the following program main( ) { char source [ ] = “orange”. strcmp(string2. Though there exists many such functions four of them will be discussed here. between string2 and b. printf(“%d\n”. getch( ). In the second printf statement the arguments to strcmp() are string2 and “banana”.g. which is the numeric difference between “orange” and “banana” ie.For string handling C provides a standard set of library functions. As both are not equal (same) the function strcmp( ) returned 13. char target [20]. Again a non-zero value is returned as “orange” and “Orange” are not equal. printf(“target:%s”. printf(“%d\n”. “Orange”)). string2)). strcpy(target. printf(“%d”. it will obviously return a 0. e. In the third printf statement strcmp( ) has its arguments “orange” and “Orange” because string1 represents “Orange”. source). main( ) { char string1 [ ] = “orange”. If both the strings are same it return a 0 or else it returns the numeric difference between the ASCII values of nonmatching characters. char string2 [ ] = “banana”. As string2 represents “banana”. strcmp(string1. printf(“source: %s\n”. target). strcpy( ) Function The function copies one string to another for e. The strcmp( ) Function This function is used to check whether two strings are same or not. “banana”).q.

h) There are two groups of string functions defined in the header <string. char target [30] = “Hello”. arr. } The output would be string = Bamboozled length=10 string = Humpty Dumpty length = 13 while calculating the length of the string it does not count ‘\0’. printf(“\n string = %s length = %d”.return s. len1 = strlen(arr).h> .g.  n is of type size_t  c is an int converted to char. len2 = strlen(“Hunpty Dumpty”).ct) __________ copy string ct to string s including ‘\0’ . source). . source).The first have names beginning with str and the second have names beginning with mem except for memmove function. len2). Here is an example of strcat( ) at work.strcat( ) This function concatenates the source string at the end of the target string for e. “Bombay” and “Nagpur” on concatenation would result in to a string “Bombay Nagpur”. “Humpty Dumpty”. Its usage is illustrated in the following program. char *strcpy(s. In the following table  s& t are of type char *  cs and ct are of type const char *. (string. printf(“\n target string = %s”. len1). The behavior is undefined if copying takes place between overlapping objects. printf(“\n source string = %s”. main( ) { char source [ ] = “Folks”. len 2. target). } And here is the output source string = folks target string = Hello folks strlen( ) This function counts the number of characters present in a string. main( ) { char arr[ ] = “Bamboozled” int len1. strcat(target. printf(“\n string = %s length = %d”.

ct. void * memchr(cs. A sequence of calls strtok(s.ct) __________ return pointer to first occurrence in cs of any character of string ct.c)___________ return pointer to last occurrence of c in cs or NULL if not present.0 if cs=ct or >0 if cs>ct. searching from just past the end of the previous one. The string ct may be different on each call.return <0 if cs <ct 0 if cs=ct or >0 if cs >ct. n is of type size_t. s and t are of type void * cs and ct are of type const void *.n)___________ same as memcpy except that is works even if the objects overlap.c.ct.n)__________compare atmost n characters of cs to string ct. it terminates that by overwriting the next character of s with ‘\0’ and returns a pointer to the token. void *memcpy(s. size_t strspn(cs.The first call in a sequence has a non NULL s.n)_______________compare the first n characters of cs with ct. return s.ct. char *strcat(s. char *strpbrk(cs. the intent is an interface to efficient routines. void *memset(s. char *strchr(cs.ct) __________return length of prefix of cs consisting of characters not in ct. return as with strcmp.n) _______________place character c into first n characters of s. or NULL if none are present. char *strncat(s.c. Char *strtok(s. int memcmp(cs. In the following table.ct.char *strncpy(s.n)__________ concatenates at most n characters of string ct to s terminate s with ‘\0’ . c is an int converted to an unsigned char. Strtok returns NULL when no further token is found.n)_________ copy at most n characters of string ct to s .ct) __________ strtok searches s for tokens delimited by characters from ct. pad with ‘\0’ s if t has fewer than n characters. char *strrchr(cs.ct)_____________ compare string cs to string ct . size_t strcspn(cs. or NULL if not present among the first n characters. return s.ct) __________ return length of prefix of cs consisting of characters in ct. FUNCTIONS . char *strerror(n)___________ return pointer to implementation defined string corresponding to error end. Functions meant for manipulating objects as character arrays.ct. int strcmp(cs. returns the next such token.return s.ct) splits s into tokens.n) ___________copy n characters from ct to s and return s.ct)____________ concatenate string ct to end of string s.return <0 if cs<ct . The mem….ct.c)____________ return pointer to first occurrence of c in cs or NULL if not present .return s. void * memmove(s. int strncmp(cs.n) _____________ return pointer to first occurrence of character c in cs. each delimited by a character from ct. each subsequent call. indicated by a NULL value of s. It finds the first token in s consisting of characters not in ct. size_t strlen(cs) ___________ return length of string cs.

Even main( ) can be called from other function. ……. } function name( ) { statements. and it is nothing but the main( )... getch( ).. Uses of the function: 1. And any function can be called from any other function. } Some Important Points to remember when doing the Function Concepts:  Any C program contains atleast one function. it is left for the user to keep how many functions he/she want to keep can keep in the program. } A( ) { statements. Writing functions avoids rewriting the same code over and over. Let us see the general form of the function which is given below. Syntax: void main( ) { statements..A Function is a “self-contained block of statements that perform a coherent/specific task of same kind”. 2.  After each function has done its executions the controller will return back to the main( ).  A function gets called when the function name is followed by a semicolon.and the execution starts from the main part or we call the starting point of the program. …………. Using functions it becomes easier to write programs and keep track of what they are doing. function name( ). main( ) { A( ). //Here “A” is a function and end with semicolon here. ………….  There is no limit on the number of function that might be present in a C program. statements.and the program ends. . For example. Every C program can be thought of as a collection of these functions.

…………. }  A function can be called from other function. main( ) { statements. For example. { statements. { statements( ). main( ) { A1( ). but if we give the order the function is very easy and readable to the user. } A2( ) //Here A2 will execute the statements after the A1 function { statements. //Here A1 & A2 are two functions A2( ).. } } . main( ) { A( ). For example. main( ). } A( ) { statements. }  The order in which the function are defined in a program and the order in which they get called not necessarily are same. A( ). such a process is called “Recursion”. //Here A( ) function is defined inside another function. }  Any function can be called any number of times. A function can call it is wrong function to call.…………. but a function cannot be defined in another function. } A1( ) //Here A1 will execute first because in the main function A1 function is called first and then go to the A2 function. For example. . A( ). main( ).

well- defined task.scanf( ). If a program is divided into functional parts. Main is an example of user-defined functions. whenever the function is “called”) from some other portion of the program.e. Information is passed via special identifiers called arguments or parameters and return via the return statement. It facilitates top-down modular programming as shown . debug and test. A function will carry out its intended action whenever it is accessed (i. However a user-defined function can later become a part of the C program library.…… Here name itself is telling that Library functions means it is already defined in the C programming.A1( ).scanf functions belong to category of library functions. The same function can be accessed from several different places within a program. printf . Once the function has carried out its intended action. library functions and user-defined functions. A( ). 1.A2( ). then each part may be independently coded and later combined into a single unit. The strengths of C language is that C functions are easy to define and use. control will be returned to the point from which the function was accessed.etc. This sub sectioning approach clearly results in a number of advantages. testing and maintaining becomes difficult. printf( ). A function is a self-contained program segment that carries out some specific. A program may become too large and complex and as a result the task of debugging. And the User-defined functions means which are defined by the Users/programmers. These subprograms called functions are much easier to understand.C functions can classified into 2 categories namely. • User-defined functions Ex.. The main distinction between these two is library functions are not required to be written by us. Some functions however accept information but do not return anything.  There are basically two types of functions: • Library functions Ex. Generally a function will process information that is passed to it from the calling portion of the program and return a single value. Where as a user-defined function has to be developed by the user at the time of writing a program.

type2 arg2. The length of a source program can be reduced by using functions at appropriate places. This factor is particularly critical with micro computers where memory space is limited.type2. A function may be used by many other programs this means that a C programmer can build on what others have already done.. and (optionally) a set of arguments. name represents the function name and type1. 3.typen represents the data types of the arguments arg1. The first line of a function definition contains the type specification of the value returned by the function.The data types are assumed to be of int . 4. It is easy to locate and isolate a faulty function for further investigations. In general terms. separated by commas and enclosed in parentheses.arg3. the high level logic of the overall problem is solved first while the details of each lower level function are addressed later. followed by the function name.…argn . data-type name(type1 arg1. from scratch. instead of starting over.type3…. 2.arg2. Main program Function1 Function2 Function3 Function4 Function5 In this programming style.An empty pair of parentheses must follow the function name if the function definition does not include any arguments. and body of the function. } where data-type represents the data type of the item that is returned by the function. Definition: A function definition has two principal components the first line (including the arguments declarations). Each argument is preceded by its associated type declaration . the first line can be written as.type3 arg3 ……typen argn) { //function body.

} Any function can call any other function. The Form of C Functions: All functions have the form function-name(argument list) Argument declarations.The corresponding arguments in the function reference are called actual arguments since they define the data items that are actually transferred. return c1. __________________ __________________ return (expression). { local variable declarations.Hence the names of the formal arguments need not be the same as the names of the actual arguments in the calling portion of the program. infact this is one of the main features of using functions. A function can be called more than once. Arguments The arguments are called formal arguments because they represent the names of the data items that are transferred into the function from the calling portion of the program. char lower_upper(char c) { //function body char c1. } Scope of the arguments The identifiers used as formal arguments are local in the sense that they are not recognized outside of the function . They are also known as formal parameters . Each formal argument must of the same datatype.if they are not shown explicitly. executable statement2. . even if the data types are integers. Ex: Consider the function which converts a lower case letter to upper case. c1=(c>=’a’ && c<=’z’)?(‘A’+c-‘a’):c. executable statement1. however as the data item it receives from the calling portion of the program. However the omission of the data types in this considered poor programming practice.

_______________________ } function3() { _____________________ _____________________ } Ex: calling a function lower_upper in the main function. _______________ } Category of functions A function. main() { char c. may belong to one of the following categories. main() { ________________________ ________________________ function1(). depending on whether arguments are present or not and whether a value is returned or not.The following example illustrates the flow of control in a multifunction program. Category 1: functions with no arguments and no return values Category 2: functions with arguments and no return values Category 3: function with arguments and return values Category 4: function with no arguments and return values .//calling function2 ________________________ ________________________ function1().//calling function1 ________________________ } function1() { _______________________ _______________________ } function2() { ______________________ ______________________ function3().//calling function1 ________________________ ________________________ function2(). __________ c=lower_upper(‘d’).

} } . return a. ------------ function2().Category 1: When a function has no arguments. function1() Values of args function2(f) { { ---------. function1() No input function2() { { -------. function1() Values of arguments function2(f) { { ---------. ---------- ---------. ------------ } } Category 2: When a function has arguments but no return values it receives data from calling function but calling function does not receive any value from called function. Similarly when no return value calling function will not receive any data from called function. Function result ---------- function2(e). ---------- ---------. In effect there is no data transfer between calling and called functions. No return Value ---------- function2(e). No output ------------ -------. it does not receive any data from calling function. ---------- } } Category 3: When a function has arguments with return values it receives data from calling function and calling function receives a value from called function.

a3….a2. actual arguments main() { ------------- function call function1(a1.Category 4: When a function has no arguments but return values it does not receive any data from calling function but calling function receives a value from called return a. ---------- ---------. If.. Suppose that there is a section of code in a program that calculates area of a triangle. Note: The actual and formal arguments should match in number.…. The values of actual arguments are assigned to the formal arguments on a one to one basis. function1() No arguments function2() { { Instead we would prefer to jump to a ‘section of code’ that calculates area and then jump back to the place from where you left off. Starting with the first argument as shown. type and order. } } In the above . . later in the program we want to calculate the area of a different triangle we won’t like to write the same instructions all over again. { --------------- -------------- } formal arguments WHY USE FUNCTIONS Two reasons: (i) Writing functions avoids rewriting the same code over and over.f3. ----------- } called function function1(f1. This section of code is nothing but a function. function1 is calling function and function2 is called function. return Value ---------- function2().

always returns an integer value. y = x * x. then it is necessary to explicitly mention so in the calling functions as well as in the called function.b. b = square (a).g: main ( ) { float a. The following program segment illustrates how to make square ( ) capable of returning a float value. (a) Functions declaration and prototypes Any function by default returns an int value. &a ). printf (“\n Enter any number”). a. and each activity placed in a different function. .b). “ a. b. e.000000 Here 6 is not a square of 2. printf (“\n square of % f is % f”. printf (“\n square of % f is % f. printf (“\n Enter any number “).5 this happened because any C function. If we desire that a function should return a value other than an int. If the operation of a program can be divided in to separate activities. } float square (float x) { float y. scanf (“\% f”.(ii) Using functions it becomes easier to write programs and keep track of what they are doing. scanf (“%f” &a). float a.5 square of 2. by default. main ( ) { float square ( ). Separating the code in to modular functions also makes the program easier to design and understand.5 is 6. b). then each could be written and checked more or less independently. b = square (a). return (y). } Enter any number 2. } square (Float x) { float y.

printf (“\na = % d b = % d”. f = factr (a). Such function calls are called ‘calls by value’ by this what it meant is that on calling a function we are passing values of variables to it.b). a.2500000 CALL BY VALUE In the preceding examples we have seen that whenever we called a function we have always passed the values of variables to the called function.b).5 is 6. y= x *x.5 square of 2. x = y. t = x. } Enter any number 2. x = 20 y = 10 a =10 b =20 . x. y). the following program illustrates this main ( ) { int a = 10. The example of call by value are shown below . printf ( “\n x = % d y = % d” . b. b=20. } The output of the above program would be. With this method the changes made to the formal arguments in the called function have no effect on the values of actual argument in the calling function. In this method the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. sum = calsum (a. return ( y). y = t. swapy (a. c). } swapy (int x. int y) { int t.

t = *x *x = *y. &b). Here x and y are called the actual arguments Formal arguments—these are the arguments used in the unction declaration. main ( ) { int a = 10. a = gcd (x. They are available to all the functions. which are specified in the function call.CALL BY REFERENCE In the second method the addresses of actual arguments in the calling function are copied in to formal arguments of the called function. Static variables—they are variables. } The output of the above program would be a = 20 b =10 Actual and formal arguments Actual argument—these are the arguments. y). b =20. int * y) { int t. consider. a. However they are available even outside the function in which they are declared. are called local variables. Here m and n are called the formal arguments Global and local variables Global variable—the variables. . called as global variable. } swapr (int *x. By default. printf (“\n a = %d b= %d”. They can be used only within the function in which it is declared. consider int gcd (int m. swapr (&a. which are declared local to a function. which are declared outside all the functions (including the main) is. *y = t. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them the following program illustrates this. all the variables are automatic variables. b). For example. which are declared within a function. int n). Automatic and static variables Automatic variable—they are created when the function block is entered and removed when the function is terminated. Local variable—the variables. For example.

fact=3*factorial(2). When we write recursive functions. The factorial of a number n is expressed as a series of repetitive multiplications Factorial of n=n(n-1)(n-2)……1. 2*factorial(1) Once again. else fact=n*factorial(n-1). if(n==1) return 1. factorial is called with n=1. For example. The sequence of operations can be summarized as follows: Fact=3*factorial(2) =3*2*factorial(1) =3*2*1 =6 Recursive functions 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. the function will never return. } let us see how to work the recursion function: Assume n=3. This process of calling itself is known as recursion. { int fact. will be evaluated. Factorial of 4=4*3*2*1=24 A function to evaluate factorial of n is factorial(n) int n.In fact it can even access itself. That is. Otherwise. the function returns 1. Ex: The evaluation of factorials of a given number. Since the value of n is not 1 the statement fact=n*factorial(n-1). return fact. This time. we must have an if statement somewhere to force the function to return without the recursive call being executed. . this call will return the following value.Recursion A function can access other functions . will be executed with n=3. The expression on the right-hand side includes a call to factorial with n=2.

swapv(a.This means that the called function is given the values of its arguments in temporary variables rather than originals. temporary copy. } swapv(int x. printf(“\n a=%d b=%d”. the call largest(a. x=y. } The parameter n is used as a temporary variable.b). there is no longer a need for the variable i. Arguments –Call by Value In C.Functions with arrays Like the values of simple variables.a. To pass an array to a called function. y=t. without any y) { int t. and the size of the array as arguments. It can only alter its private. it is sufficient to list the name of the array. whatever is done to n inside power has no effect on the argument that power was originally called with. The called function cannot directly alter a variable in the calling function.b). . This means that using these addresses we would have an access to the arguments and hence we would be able to manipulate them. and is count down ( a for loop that runs backwards) until it becomes zero. b=20. all function arguments are passed “by value” . In the second method call by reference the addresses of actual arguments in the calling function are copied into formal arguments of the called function. Ex: main() { int a=10. t=x.n). For example. it is also possible to pass the values of an array to a function.

&b). *y=t. But if desired. } Note that this program manages to exchange the values of a and b using their addresses stored in x and y. printf(“\n a=%d b=%d”. . This means in general you cannot alter the actual arguments. *x=*y. int *y) { int t. it can always be achieved through a call by reference. b=20. t=*x.b). Ex: main() { int a=10. swapr(&a. Usually in C programming we make a call by value. } swapr(int *x.a.

Static variables 4. External variables 3. But. Hence. Ex: int number. A variable in C can have any one of the four storage classes: 1. it is a local variable to the function1 …………… } in the above example n1 can not be used in main function.STORAGE CLASSES Variables in C can have not only datatype but also storage class that provides information about their location and visibility. Internal variables are those which are declared with in a particular function. automatic variables are also referred to as local or internal variables. It is very important to understand the concept of storage classes and their utility in order to develop efficient multifunction programs. . they are private (or local) to the function in which they are declared. it is a global variable main() { …………… } function1() { int n1. They are created when the function is called and destroyed automatically when the function is exited. So. number can be used in both main and function1 being a global variable. So. longevity has a direct effect on the utility of a given variable. Automatic variables 2. The variables can be categorized into internal or local and external or global. It can be used only in function1 because it is local variable to that. While external variables are declared outside of any function. The storage class decides the portion of the program with in which the variables are recognized. Automatic variables: Automatic variables are declared inside a function in which they are to be utilized. Longevity refers to the period during which a variables retains a given value during execution of a program. Register variables Scope & Lifetime of variables: The scope of each variable determines over what part(s) of the program a variable is actually available for use.

A variable declared inside a function without storage class specification is, by default, an
automatic variable.

auto int number;
The storage class of the variable number in the above example is automatic.
Storage : Memory
Default value :garbage value.
Scope :Local
Life :Till the control remains within the block in which the
variable is defined.

Register Storage class

Instead of keeping in main memory where normal variables are stored we can tell the
compiler to store a variable in CPU registers. This makes fast access to variables.
This is preferred for frequently accessed a variable which leads to faster execution of

Ex: register int count;

ANSI standards does not restrict its application to any particular data type, most
compilers Allow only int or char variables to be places in the register. Since there is a
limit on no of variables that can be stored in the register, when the limit is reached C will
automatically convert register variables into non register variables.

External Storage class:
An external variable is global variable. It is declared outside the all functions. Yet is
available to all functions that care to use them.

int i;
extern int i;

printf(“\n i=%d”,i)

int y;

In the above main can not access y as it has been declared after the main function.
To know the use of external variable let us consider following example.

extern int y;//external declaration
extern int y;//external declaration
int y;//definition

In this main and function1 y can be accessed as it has been declared after both the
functions. The external declaration of y inside the functions informs the compiler that y is
an integer type defined somewhere else in the program.
The extern declaration does not allocate storage space for variables.

Multifile programs

In real-life programming environment we may use more than one source files which may
be compiled separately and linked later to form an executable object code. This approach
is useful because any change in one file does not affect other files thus eliminating the
need for recompilation of the entire program.

Multiple source files can share a variable provided it is declared as an external.
Variables that are shared by two or more files are global variables and therefore we must
declare them accordingly in one file and then explicitly define them with extern in other

file1.c file2.c
main() int m;/* global variable */
{ function2()
extern int m; {
int i; int i;
---------- -------------
----------- -------------
} }
function1() function3()
{ {
int j; int count;
--------- ----------
--------- ----------
} }

The function main in file1 can reference the variable m that is declared as global in file2.
function1 cannot access the variable m. If , however the extern int m; statement is placed
before main, then both the functions could refer to m.This can also achieved by using
extern int m; statement inside each function in file1.

The extern specifier tells the compiler that the following variable types and names have
already been declared elsewhere and no need to create storage space for them. It is the
responsibility of the linker to resolve the reference problem. It is important to note that a
multi-file global variable should be declared without extern in one (and only one) of the
files. The extern declaration is done in places where secondary references are made. If we
declare a variable as global in two different files used by a single program, then the linker
will have a conflict as to which variable to use and, therefore, issues a warning.

When a function is defined in one file and accessed in another, the later file must include
a function declaration. The declaration identifies the function as an external function
whose definition appears elsewhere we usually place such declarations at the beginning
of the file, before all functions. Although all functions are assumed to be external, it
would be a good practice to explicitly declare such functions with the storage class

static float y. ---------- ----------- } } function1() function3() { { int j. depending on the place of declaration. { function2() int i. { ----------. file1. Internal static variables are those which are declared inside a function. Ex: it can be used count the number of calls made to a function.c file2. int i. Therefore these are used to retain values between function calls. --------- --------- } } static int x. ----------. int count. .Static variables These variables persist until the end of the program.c main() extern int m. Therefore these are similar to auto variables except that they remain in existence or alive throughout the remainder of the program. A variable can be declared static using the keyword static like. A static variable can be either internal type or external type. The scope of internal static variables extends upto the end of the function in which they are defined.

Pointer variables can be used in arithmetic operations in place of ordinary variables. we need to prefix the pointer variable with an asterisk. int j = i * 2. if (i > 100) printf ("Hello"). suppose that we want to find out if i is an even or odd number. Then.POINTERS Pointer variables can be used in expressions in place of ordinary variables. For example. Then the following two arithmetic operations are equivalent. For example. For this purpose. the following two expressions are the same. else printf ("Odd"). Note that we have simply substituted i with *p. consider the following: int i = 100. we can have the following equivalent if conditions. else printf ("Odd"). int i = 100. int *p = &i. if (j == 0) printf ("Even"). int j = *p / 2. int j = i / 2. we need to prefix the pointer variable with an asterisk. For example. suppose that we want to multiply the value of i by 2 to compute the value of another variable j. For example. Now we can use *p wherever we would use i. ‘C’ program to illustrate the use of pointers in arithmetic operations. consider the following. int *p = &i. For this purpose. int j = *p * 2. if (j == 0) printf ("Even"). Similarly. if (*p > 100) printf ("Hello"). . Now we can use *p wherever we would use i.

months[month2]). int mmdd.”Jun”. We will define a structure. which may be used to declare many other variables in that format. char author[15]. // take month alone printf(“\nFirst month is %s”. which will define details of a book—title of the book. printf(“\nEnter first date (mmdd) “).”Apr”.”Nov”. author of the book.”Jul”. “Aug”.mmdd). date2. Use your structure that accept two different dates in the format mmdd of the year and do the following: Write a C program to display the month names of both dates. printf(“\nSecond month is %s”. float price. we want a single collection to hold an integer and a character variable. }. month1 = date1. // take month alone month2 = date2.”Dec”}.months[month1]).”Mar”.&date2. 500. It can be initialized as below: static struct book mybook = {“Data Structure”.0}. scanf(“%4d”. int month1. “tenenbaum”. scanf(“%4d”.”Oct”. struct mydate { int yyyy.”Jan”. } . This is possible only through a structure. 200.mmdd). printf(“\nEnter second date (mmdd) “). Look at the declaration given as follows: struct book { char title[20]. It is declared as below. main() { struct mydate date1. Define the structure to represent a date.&date1. price of the book and the number of pages it has.”Feb”.mmdd / 100.”Sep”.mmdd / 100.”May”. char *months[] = {“”. month2. }. int pages. For example. It creates a format.STRUCTURES: Structures help to organize complex data in a more meaningful manner.

printf(“%4d”.emp1. int DA.month). float basic.00.emp1.year).2f”. struct employee { int struct salary { int basic. Name : %s.empno. }. C program to illustrate the concept of structure within structure.joindate. int month. { char name[20].”Muthu”. } . main() { struct employee emp1 = {100. int year. char name[20].}. int empno. struct date { int day.emp1. This means one structure is defined within another structure.Structure within structure A Structure within a structure means nesting of structures. }. The example is given below: struct employee.”.emp1.10. }.5000. printf(“\nJoindate %2d. struct date joindate. }.%2d.joindate.basic). Basic : %5. printf(“\nEno : %d.12.

total + student[i]. int marks2.sub2 + student[i]. for (i = 0. }. each element of the array representing a structure variable. { = total.sub3. i <= 2. we may declare an array of structures. we may use a template to describe student name and marks obtained in various subjects and then declare all the students as structure variables. int sub2. i++) { student[i]. = student[i].total. 45.sub1 = total. static struct marks student[3] = { {56. struct marks { int sub1. 75}}.sub1 + student[i].sub2. }. } C program to calculate student-wise total for three students using an array of structure. int marks3. While analyzing the marks obtained by a class of students. 65. } printf(“\nSTUDENT TOTAL\n\n”).sub2 + student[i]. total.sub3. {45. static struct marks total. 55. total. main() { static struct marks IIIMCA[2] = {{78.sub1. int total.sub1 + student[i]. 76}}. . 65}. 87.sub3 = total. 76.sub2 = total. main() { int i. total. In such cases. int sub3. 87}.sub3 + student[i]. {67.Array of structures Consider a simple example. 75}. struct marks { int marks1.

total. total. i <= 2. total.for (i = 0.myptr->paise).total).25}. } .sub1. int paise. total.myptr->rupees. main() { struct currency mycurr = {123. } showit(struct currency *myptr) { printf(“\nRupees %d. “Subject 2“. }.total).sub2. printf(\nGrand Total = %d”. i++) printf(“\nStudent[%d] %d”.%d”. printf(“\nSUBJECT TOTAL\n\n”). student[i]. i + 1. showit(&mycurr). “Subject 3“. printf(“%s %d\n%s %d\n%s %d\n”. } C program to illustrate the use of structure pointer.sub3). “Subject 1“. struct currency { int rupees.

The contents are deleted. Filename is a string of characters that make up a valid filename for the operating system. When the mode is ‘writing’ a file with the specified name is created if the file does not exist. This pointer which contains all the information about the file is subsequently used as a communication link between the system and the program. 2. The second statement also specifies the purpose of opening this store PROG. one of the following things may happen: 1. we must specify certain things about the file. all files should be declared as type FILE before they are used. Purpose. For example. to the operating system. It may contain two parts. The first statement declares the variable fp as a “pointer to the data type FILE”. Following is the general format for declaring and opening a file: FILE *fp. A file with the specified name is created if the file does not exist. 2. Data structure. fp = fopen(“ filename”. the file is opened with the current contents safe. Examples: Input. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. FILE is a defined data type. As stated earlier. a primary name and an optional period with the extension. They include: 1. They should be enclosed in double quotation marks.FILES If we want to store data in a file in the secondary memory. Therefore. The mode does this job. 3. When we open a file. Mode can be one of the following: r open the file for reading only.out Data structure of a file is defined as FILE in the library of standard I/O function definitions. “ mode”). . w open the file for writing only. FILE is a structure that is defined in the I/O library. if the file already exists.C Student c Text. a open the file for appending (or adding) data to it. Filename. we may write data to the file or read the already existing data. we must specify what we want to do with the file. When the purpose is ‘appending’. When trying to open a file. Note that both the filename and mode are specified as strings.

p1 = fopen(“data”. The file data is opened for reading and results is opened for writing. and if it exists. then the file is opened with the current contents safe. otherwise an error occurs. Many recent compilers include additional modes of operation. “w”). an error will occur. the results file already exists. If data file does not exist. p2 = fopen(“results”. w+ Same as w except both for reading and writing. If the purpose is ‘reading’. .3. In case. a+ Same as a except both for reading and writing. *p2. This number however depends on the system we use. Consider the following statements: FILE *p1. We can open and use a number of files at a time. They include: r+ The existing file is opened to the beginning for both reading and writing. its contents are deleted and the file is opened as a new file. “r”).

the source and destination are typically registers. keeping track of files and directories on the disk. • Multi-Tasking: Allows more than one program to run concurrently. ensuring that unauthorized users do not access the system. • Multi-Threading: Allows different parts of a single program to run concurrently. can run. The application programs must written to run on top of a particular Operating System. The primary goal of an operating system is thus to make the computer system convenient to use. Windows: This Operating System is mainly used for the Graphical User Interface (GUI). etc The most important program that runs on a computer is Operating System. Unix 4. BUSES A Bus is a set of Lines(wires) designed to transfer all bits of a word from a specified source to a specified destination on the same or a different I. DOS (Disk Operating System): This Operating System for IBM range of microcomputers was developed by a team of Microsoft’s programmers. this is an Operating System basically developed for 16 bit microcomputers.Therefore. sending output to the display screen.C(Integrated Circuit). that is. Linux. such as recognizing input from the keyboard. Operating Systems provide a software platform on top of which other programs. Secondary goal is hardware resource management. Operating System can be classified as follows: • Multi-User: Allows two or more users to run programs at the same time. capable of transmitting data in one direction only. • Multi-Processing: Supports running a program on more than one CPU. 1.It acts according to the user requirement. called application programs.S) can be defined as system software which acts as the Interface between user and the system and manages the resources in efficient way. they are. Every general purpose computer must have an Operating System to run other programs. A Bus can be unidirectional. the cost of the wires or cables used must also be taken into account. Operating Systems perform basic tasks. They are different types of Buses. create and manage files and facilitate the use of peripheral devices such as disks.OPERATING SYSTEM Operating System (O. If these Buses are long. or it can be bidirectional. . They are different O. The Operating System is also responsible for security. and controlling peripheral devices such as disk drives and printers. printers etc. the Operating System also called as MS-DOS. are not real-time. 2.S. It is a collection of programs on a floppy disk designed to help run the programs. Some Operating System permits hundreds or even thousands of concurrent users. General purpose Operating Systems. 3. such as DOS and UNIX. • Real-Time: Responds to input instantly.

• Data compression. sounds.24. Address Bus: The Address Bus consists of 16. there is one standard interface for connecting External Modems to computers called RS-232. or it can send data out to memory or to a port on these lines. images. telephone or cable lines. There are also Modems that come as Expansion boards that you can insert into a vacant expansion slot. It is nothing but a group of wires to carry bits. On theses lines the CPU sends out the address of the memory location that is to be written to or read from. or 32 parallel signal lines.20.These are sometimes called onboard or Internal Modems. BROWSER A Browser is a computer program that resides in your computer enabling you to use the computer to view WWW documents and access the Internet taking advantage of text formatting. This means that the CPU can read data in from memory or from a port on these lines.Firefox and Internet Explorer are currently the leading “graphically browsers” in the world (meaning they facilitate the viewing of graphics such as images and video and more). hypertext links. and other features. System Bus: The System Bus is a communication path between the microprocessor and peripherals. 16. While the Modems interfaces are standardized. motion. whereas information transmitted over telephone lines is transmitted in the form of Analog waves. 3. which almost all personal computers have. Computer information is stored digitally. • Fax capability. • Auto-answer. Data Bus: The Data Bus consists of 8. for example.32 parallel signal lines. Simply we can say that bus is used to carry the data. If the CPU has N address lines. MODEM A Modem is a device or program that enables a computer to transmit data over. 1. There are . then it can directly address 2 Power of N memory locations. 2. we can say that Address Bus is used to carry the address. Aside from the transmission protocols that they support.Simply. A modem converts between these two forms (Analog to Digital waves and vice- versa). • Voice/data. Consequently any External Modem can be attached to any computer that has an RS-232 port. The number of memory locations that the CPU can address is determined by the number of address lines. The data bus lines are bidirectional. a number of different protocols for formatting data to be transmitted over telephone lines exist.Fortunately. the following characteristics distinguish one modem from another: • Bps (bits per seconds). • Flash memory.

. The Internet itself does not contain information.Netscape. and view programs that run on practically any software in the world. . INTERNET The Internet is a network of network. view images. Fire Fox. Each runs software to provide or “serve” information and/or to access and view information. providing your computer has the hardware and software to do these things. linking computers sharing the TCP/IP protocols. fastest growing activity on the Internet’s readers.g. animations and videos.Most offers many of the same features and can be successfully used to retrieve documents and activate many kinds of programs.g. Mozilla. It would be more correct to say it was found through or using the Internet.other browsers (e. When you log onto the Internet using a Web Browser(e. interpreting XML in a way analogous to how browsers interpret HTML. • Gopher • The WWW (World Wide Web or “the Web”).Mozilla. • Telnet or remote login • FTP or File Transfer Protocols. listen to sound files. • Electronic mail (e-mail). you are viewing documents in the World Wide Web. It is a slight misstatement to say a” document was found on the Internet”. download them to diskette. It is HTML and other programming embedded within HTML that makes possible Hypertext. WORLD WIDE WEB The World Wide Web or WWW or The Web is the largest. which are areas in a page or buttons or graphics on which you can click your mouse button to retrieve another document into your computer. Hypertext is the ability to have Web pages containing links. Safari and Opera) . and keep track of where you’ve been and site you want to “bookmark” or “Add to Favorites”. The Internet is the transport vehicle for the information stored in files or documents on another computer. Computers on the Internet may use one or the entire following Internet Services. Netscape and Internet Explorer both offer the ability to e-mail documents. Internet Explorer. You can retrieve documents. The basic foundation on which the WWW functions is the programming language called HTML. It can be compared to an International communications utility servicing computers.. This “click ability” using Hypertext links is the feature which is unique and revolutionary about the Web.The WWW incorporates all of the Internet services. speck and hear voice.Opera.Safari). print them. It is sometimes compared to a giant International plumbing system.. The main way in which browsers differ is in the convenience features they offer for navigating and managing the Web and all the URLs you may want to keep track of.

For instance. we can radiate all our links out from a central hub. factory or an organization housed in a building. Such adaptors are generally 16 bit. e-commerce. 1. 1. Internet shopping through the Networks. Star Topology . With the Computer Network we have so many uses. The design of a LAN involves the selection of a Topology and an architecture that guides the interconnection of components. 3. graphics. The data becomes available on online. Based on the requirements the Computer Networks are classified as follows: • LAN(Local Area Networks) • WAN(Wide Area Networks) LAN (Local Area Networks): A LAN is a network of closely located computers connected by transmission media and adaptors in such a manner that the system allows its users to communicate and share computing resources. better efficiency can be achieved by linking its various computerized departments for that we are using the Computer Networks. or we connect all the components on point to point basis. Network Topology: The term topology means the “structure consisting of paths and devices that provide” the necessary communication interconnection among the components of the network. Respectively. We can link everything together on a line. these topologies are. There are four choices of arranging the components. motion pictures etc can be communicated at extremely fast rate through networks. a user can get the Exam results and any type of reservations through Internet. It is confined to a small sized geographical area and depends upon transmission media of moderate to high data rate. The user gets better services such as email.” A Computer Network consists of two or more computers that are linked in order to share resources exchange files. we can join the ends of this line to form a ring.COMPUTER NETWORKS In large and wide spread organizations. supporting Full-duplex mode of transmission of data. Plug and Play network adaptors are used in LAN instructions. The transmission rate is in the tune of 10 to 20 Mbps.The LAN is generally contained in an office. Network is that “a group of computers connected each other is called Network”. Linear Bus Topology 2. The data consisting of text. or allow electronic communication”. sound. Ring Topology 3. Types of Networks A group of computers connected each other is called as Network. 2.

2. WAN protocols are. Frame Relay.WAN interconnect LAN’s located in any part of the world. therefore. 1.WAN (Wide Area Networks): A wide area network is a computer network that spreads a region. The LAN’s are connected with the help of WAN back bones. 3. Where LAN market has grown at the rate of 175%. the transmission is comparatively costly. X-25 Protocol. Generally WAN’s use satellites as the primary transmission on media and. . country or whole of the world.The popular. the WAN growth has been relatively slow at 40%. ATM.