You are on page 1of 74

TABLE OF CONTENTS CHAPTERS Chapter 1 (Introductory Concepts Of C) Chapter 2 (Data Types, Variables And Constants Chapter 3 (Operators And

Expressions) Chapter 4 (Control Statements) Chapter 5 (Arrays And Strings) Chapter 6 (Functions) Chapter 7 (Pointers) Chapter 8 (Structures) Chapter 9 (File Handling In C) PAGE 02 05 09 11 40 48 55 60 65

CHAPTER 1 INTRODUCTORY CONCEPTS OF C INTRODUCTION C is a structured programming language. Its instructions consist of terms that resemble algebraic expressions, augmented by certain English keywords such as if, else, for do and while, while etc. C also contains certain additional features, however, that allow it to be used at a lower level, thus bridging the gap between machine language and more conventional high-level languages. It has a relatively small instruction set, though actual implementations include extensive library functions which enhance the basic instructions. C compilers are commonly available for computers of all sizes, and C interpreters are becoming increasingly common. The compilers are usually compact, and they generate object programs that are small and highly efficient when compared with programs compiled from other high-level languages. The interpreters are less efficient, though they are easier to use when developing a new program. HISTORY OF C C was originally developed in the 1970s by Dennis Ritchie at Bell Telephone Laboratories, Inc. (now a part of AT&T). It is an outgrowth of two earlier languages, called BCPL and B, which were also developed at Bell laboratories. One question may strike in your mind that why a language should be given such a cryptic name as C, it drives from the fact that it is based on an earlier version written by Ken Thompson, another Bell Laboratories system engineer. He adapted it from a language that was known by the initials BCPL, which stand for Basic Combined Programming Language. To distinguish his version of the language from BCPL Thompson dubbed it B, the first of the initials BCPL. When the language was modified and improved to its present state, the second letter of BCPL, C, was chosen to represent the new version. It is mere coincidence that the letters B and C are in alphabetic order. Some contend that the successor to C will be D, while others say it should be called P. STRUCTURE OF A C PROGRAM Every C program consists of one or more modules known as functions. One of the function must be called main. The program will always begin by executing the main function, which may access other functions. Any other function (user defined) definitions must be defined separately, either ahead of or after main function. In C, all statements are terminated with a semicolon. Novices to C frequently forget to add the semicolon ( ; ) so be on your guard ! main( ) { statement a; statement 2; .. .. }

Program 1 : is a very simple C program. You may watch yourself and try to discover what it does. /* Program for displaying a message */ # include <stdio.h> /* Library file access (commonly known as header file)*/ main() { printf(This is My first program in C); /* Execution body, output statement */ } Explanation of Program 1 The above program will print the string of characters enclosed by the double quotation marks (but not the quotes themselves). The output of the program is as follows: Output of Program 1 This is My first program in C The following features should be pointed out in above program 1. 2. 3. 4. 5. 6. The program is typed in lower cases. Hence C language is case sensitive. (Upper and Lower cases characters are not equivalent in C. The first line is a comment that identifies the purpose of a program. The second line is a reference to a special file (called stdio.h) which contains information that must be included in the program when it is compiled. The inclusion of this required information will be handled automatically by compiler. The third line is heading for the function main. The empty parentheses following the name of the function indicate that this function does not include any arguments. The remaining line of the program is enclosed within a pair of braces. Notice that these braces line up with the letter m of the word main. This alignment is not strictly necessary, but it makes the program more readable. At last, notice the liberal use of spacing and indentation, creating white space within the program. These features are not grammatically essential, but their presence is strongly encouraged as a matter of good programming practice.

Exercise 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 Name four different types of data? What is a computer program? What is machine language? How does machine language differ from high-level language? What is meant by compilation? What is meant by interpretation? How do these two process differ? What is difference between source and object program? What is C++? What is the relationship between C and C++? How can comments be included within a C program? Where can comments placed? What symbol terminates every C statement. Study the following program C program and detect some errors. Give reason why they are in error. What is the out put of the program : main{} \* This is one great program in C */ { printf( I think you are making fun of me); } (For practical) 1. 2. 3. Write a program that prints your name, age and address Write a program which can print any four lines of your favorite poem Write a program to display the following text : Computer is An electro-mechanical device Can process logical and numerical values 4. Decide what output of the following program will be, and then run it on a computer to confirm your answer #include<stdio.h> main() { printf( THIS IS SMT COMPUTER EDUCATION \n); printf(WE ARE STUDENTS OF C LANGUAGE \n tool \n); }

CHAPTER 2 DATA TYPES, VARIABLES AND CONSTANTS A character denotes any alphabet, digit or special symbols used to represent information. Following table shows the valid alphabets, numbers and symbols allowed in c: The C character set + ^ [ Data Types There are two different types of data in C programming integer and floating point. From these two we can derive two others characters and floating point. There also exits a data type called void. Data Type char int float double void Meaning A character An integer A single precision real number A double precision real number Value less Size (bytes) 1 2 4 8 0 ] * { / ~ } = \ : % | ; & < . # > _ ! ( ? )

(blank space)

AN INTRODUCTION OF VARIABLES IDENTIFIERS AND KEYWORDS Identifiers are names that are given to various program elements, such as variables, functions and arrays. Identifiers consist of letters and digits, in any order, except that the first character must be a letter. Both upper- and lowercase letters are permitted, though common usage favors the use of lowercase letters for most types of identifiers. The underscore ( _ ) can also be included, and is considered to be a letter. The following names are valid identifiers. A Roll_no a123 NAME tot_1 total_sal _age marks1

There are certain reserved words, called keywords, that have standard predefined sense in C. These words can not be used as programmer-defined identifiers.

KEYWORDS There are 32 Key words presents in C language. auto do goto signed unsigned break double if sizeof void case else int static volatile char enum long struct while const extern register switch continue float return typedef default for short union

Some C compilers also reserve the following words asm entry fortran signed

THE CONCEPT OF VARIABLE Strings and numeric values can be stored as int type in the memory of the computer for subsequent recall. Whenever the memory is used for this purpose, the programmer must assign a unique name to each such area in memory. If the arbitrary name number is used to refer to the area of memory in which a particular value is stored, number is called a variable Integer Variable C deals with several different kinds of numbers. One of the most frequently used is the whole number, usually called an integer. It is characterized by the fact that it does not have either a decimal point or a fractional portion. Some examples of integer as follows: 100 150 110 -34 -567 0

Floating Point A number containing decimal point is known as floating point or real. Programmer has to declare this kind of variable separately while writing program. Because float variable can input integer value but integer can not do same. Following are some examples of floating point values 13.6 15. 15.0 -18.45 23.986

A number such as 15 or 15.0 also is considered a floating point number, even though its fractional part is zero. The critical consideration is whether the number contains a decimal point, regardless of what follows it.

C CONSTANTS We use character, integer, float, logical and string type constants in C language. For constructing these different types of constants certain rules have been laid down. Rules For Constructing Integer Constants (a) (b) (c) (d) (e) An integer constant must have at least one digit. It must not have a decimal point. It could be either positive or negative. No commas or blank space are allowed with an integer constant. The allowed range for integer constants is -32768 to +32767.

Rules For Constructing Real Constants (a) (b) (c) (d) (e) A real constant must have at least one digit. It must have a decimal point. It could be either positive or negative. Default sign is positive. No commas or blank space are allowed with an integer constant.

Example +535.53 435.00 - 32.93 - 48.747 Rules For Constructing Character Constants (a) A character constant is either a single alphabet, a single digit or a single symbol enclosed within a pair of single inverted commas, Ex. : a, A, 5 (b) The maximum length of a character constant can be one character. (c) The valid range of character constant is 128 to +127. Rules For Constructing String Constants A collection of characters, enclosed in double quotation marks. Declarations A declaration consists of data type, followed by one or more variable names, ending with a semicolon. Example int a, b,c /* for integer type */ float a1,b2 /* for floating type */ char name[10]; char name[10]={"tanuj", "anurag" , "naveen","preeti","neelima"}; /* for character type */

DATA TYPE IN C LANGUAGE Data Type Single char Unsigned char Short signed int Short unsigned int Long signed int Long unsigned int Float Double Long double Escape Sequences Certain nonprinting characters, as the double quote (), the apostrophe ( ), the question mark (?) , and the backslash (\), can be expressed in terms of escape sequences . An escape sequence always begins with a backward slash and is followed by one or more special characters. Character Bell Back space Horizontal tab Vertical tab New line Null Escape Sequence \a \b \t \v \n \0 Range -128 to +127 0 to 255 -32768 to +32767 0 to 65535 -2147483648 to 2147483647 0 to 4294967295 -3.4e38 to + 3.4e38 -1.7e4932 to 1.7e308 -1.7e4932 to 1.7e4932 Bytes 1 1 2 2 4 4 4 8 10 Format %c %c %d %u %ld %lu %f %lf %Lf

CHAPTER 3 OPERATORS AND EXPRESSIONS There are 45 different operators are present in C Language. We are going to discuss most of these operators and there interaction with one another in this CHAPTER. There are eight types operators presents in C language 1.Arthmetic operators 2.Relational operators 3.Logical operators 4.Aassignment operators 5.Increment and decrement operators 6.Conditionals operators 7.Bitwise operators 8.Specials operators 1. Arithmetic operators C compiler provides the following arithmetic operators. Operators + * / % Meaning Addition or Unary plus Subtraction or Unary minus Multiplication Division Modulation division

2. The Relational Operators Relational operators are symbols that are used to test the relationship between two variables, or between a variable and a constant.. C has six relational operators, as defined in the following table: Operator == > < != >= <= 3. The Logical Operators Logical operators are symbols that are used to combine or negate expressions containing relational operators. C has three logical operators: AND operator use as OR operator use as NOT operator use as 4. Assignment operators
9

Meaning equal to greater than Less than not equal to (either greater than or less than) greater than or equal to less than or equal to

&& || !

Assignment operators are used to assign the results of an expression to a variable. We have seen the usual assignment operator , = . Exp: If(a == b) { statement; } 5. Increment and Decrement operators C language have two increment and decrement operators Increment operators a) pre- increment operator ++a : increment before assigning a value. b) Post- increment operator a++ : increment after assigning a value. Decrement operators c) pre-decrement operator -- a : decrement before assigning a value. d) Post-decrement operator a -- : decrement after assigning a value. Note : a++ a + 1 , + +a a + 1 --a a - 1 , - -a a 1

6. Conditional operators A ternary operator ? is available in C to constants conditional expressions of the form. Exp1 ? (Exp 2) : (Exp3); Where exp1, exp2, exp3 are expressions. Example If(a>=b) ? (a*b) : (a+b) If the condition is satisfied, then exp2 is evaluated otherwise exp3 is evaluated. 7. Bit-wise operators C has a distinction of supporting special operators called as BITWISE operators for manipulation of data at bit level. These operators are used for testing of bits, shifting them right or left. Bit-wise operators may not be applied to float or double.

10

BITWISE OPERATORS OPERATORS & | ^ << >> ~ 8. Special operators C supports some special operators of interest such as comma operator, sizeof operator, pointer operator(&and *) and member selection opertors ( . And->). Example: a) value=(x=10,y=5,x+y); MEANING Bitwise AND Bitwise OR Bitwise Exclusive Shift Left Shift Right Ones compliment

First assign the value of 10 to x, than assign 5 to y and finally assigns 15 to value. Example: b) int sum; m=sizeof(sum); returns value 2 bytes because

11

CHAPTER 4 CONTROL STATEMENTS C language possesses such decision making capabilities and supports the following statement known as control or decision making statement. 1. 2. 3. 4. if statement. switch statement. loops goto statement.

1. The if Statement General Form of if The general form of if statement looks like this : If (this condition is true) { Execute this statement ; } Example #include<stdio.h> main () { int num; printf (Enter a number greater than 5); scanf (%d, &num); if (num >5) { printf(What an obedient servant you are !); } } On execution of this program, if you type a number greater than 5, you get a message on the screen through printf(). If you type some other number the program doesnt do anything. To make you comfortable with the decision control statement one more example has been given below; study it carefully before reading further. To help you understand it easily, the program is accompanied by an appropriate flowchart. Example While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000. If quantity and price per item are input through the keyboard, write a program to calculate the total expenses.

12

/*Calculation of total expenses */ #include <stdio.h> main() { int qty, dis=0; float rate, tot; printf(Enter quantity and rate); scanf (%d %f, &qty, &rate); if (qty > 1000) { dis = 10; tot = (qty * rate) (qty * rate * dis/100); printf(\nTotal expenses = Rs. %f, tot); } Here is some sample interaction with the program. Enter quantity and rate 1200 15.50 Total expenses = Rs. 16740.000000 Enter quantity and rate 200 15.50 Total expenses = Rs. 3100.000000 2. The if-else Statement The if statement by itself will execute a single statement, or a group of statements, when the condition following if is true. It does nothing when it is false. Can we execute one group of statements if the condition is true and another group of statements if the condition is false ? Of course. This is what is the purpose of the else statement, which is demonstrated in the syntax Syntax if (condition is true ) do this ; else if (condition is true) { do this ; and this ; } Example In a company an employee is paid as under: If his basic salary is less than Rs. 1500, then HRA=10% of basic salary and DA=25% of basic. If his salary is either equal or above Rs. 1500, then HRA= Rs. 500 and DA=50% of basic. If the employees salary is input through the keyboard write a program to find his gross salary. /*Calculation of Gross salary*/
13

#include<stdio.h> main() { float bs, gs, da, hra; printf (Enter basic salary); scanf (%f, &bs); if (bs > = 1500) { hra = 500; da = bs * 50 / 100; } else { hra = bs * 10/100; da = bs * 25 /100; } gs = bs + hra + da ; printf (gross salary = Rs. } A few points worth noting .

%f, gs);

(a) The group of statements after the if upto and not including the else is known as an if block. Similarly, the statements after the else forms the else block. (b) Notice that the else is written exactly below the if. The statements in the if block and those in the else block have been indented to the right. This formatting convention is followed throughout the book, to enable you to understand the working of the program better. (c) Had there been only one statement to be executed in the if block and only one statement in the else block we could have dropped the pair of braces. (d) As with the if statement, the default scope of else is also the statement immediately after the else. To override this default scope a pair of braces as shown in the above example must be used. 3. Nested ifs It is perfectly possible to write an entire if- else construct within either the body of the if statement or the body of an else statement. This is called nesting of ifs. This is shown in the following program. /*an example of nested if elses*/ main () { int i; printf (Enter either 1 or 2); scanf (%d, &i); if (i == 1) { printf (You would go to heaven!); } else { if (i == 2) { printf (Hell was created with your mind);
14

} else { printf (How about mothers earth!); } } 4. The if-else-if Ladder Let us consider the following problem. Example The marks obtained by a student in 5 different subjects are input throught the keyboard. The student gets a division as per the following rules: Percentage above or equal to 60 First division Percentage between 50 and 59 Second division Percentage between 40 and 49 Third division Percentage less than 40- Fail Write a program to calculate the division obtained by the student. Here is the program /*Determine the division obtained by a student */ main () { int m1, m2, m3, m4, m5; float per ; printf (Enter marks in five subjects); scanf (%d %d %d %d, &m1, &m2, &m3, &m4, &m5); per = (m1+m2+m3+m4+m5)/5 ; if (per >= 60) { printf (First division); } else { if (per >= 50) { printf (Second division); } else if (per >= 40) { printf(Third division); } else { printf (Fail); } }
15

} Observe that this program uses nested ifs-elses. This leads to three disadvantages: (a) As the number of conditions go on increasing the level of indentation also goes on increasing. As a result the whole program creeps to the right. (b) Care needs to be exercised to match the corresponding ifs and elses. (c) Care needs to be exercised to match the corresponding pair of braces. All these three problems can be eliminated by usage of Logical operators that we studied in the last CHAPTER. The following program illustrates this. /*Determine the division obtained by a student */ main () { int m1, m2, m3, m4, m5; float per ; printf(Enter marks in five subjects); scanf (%d %d %d %d %d, &m1, &m2, &m3, &m4, &m5); per = (m1 + m2 + m3 + m4 + m5)/5; if (per>=60) { printf(First division) } if((per>=50) && (per < 60)) { printf (Second division); } if ((per >=40) && (per<50)) { printf (Third division); } if (per < 40) { printf (Fail division); } } Another place where logical operators are useful is when we want to write down programs for complicated logic which ultimately boil down to only two answers. For example, consider the following problem: Example A company insures its drivers in the following cases : If the driver is married. If the driver is unmarried, male & above 30 years of age. If the driver is unmarried, female & above 25 years of age. In all other cases the driver is not insured. If the marital status, sex and age of the driver are the inputs, write a program to determine whether the driver is to be insured or not. Now, we would write down programs for the above problem in 2 ways:

16

(a) Without using && and || operators (b) Using && and || operators Method (a) main() { char sex, ms; int age; printf(Enter age: ); scanf(%d,&age); printf(Enter sex :); scanf(%c,&sex); printf(marital status); scanf(%c,&ms); if(ms==M) printf(Driver is insured); else { if (sex == M) { if (age>30) printf(Driver is insured); } else printf(Driver is not insured); } else if(sex == F) if(age>25) printf(Driver is insured); else printf(Driver is not insured); } } } Method (b) As mentioned above, in this example we expect the answer to be either Driver is insured or Driver is not insured. If we list down all those cases in which the driver is insured, then they would be: (a) Driver is married. (b) Driver is an unmarried male above 30 years of age. (c) Driver is an unmarried female above 24 years of age. Since all these cases lead to the driver being insured, they can be combined together using && and || as shown in the program below:

17

/*Insurance of driver using logical operators */ main() { char sex, ms; int age; printf(Enter age: ); scanf(%d,&age); printf(Enter sex :); scanf(%c,&sex); printf(marital status); scanf(%c,&ms); if((ms == M) || (ms == U && sex == M && age > 30) || (ms == U && sex == F && age > 25)) printf(Driver is insured); else printf(Driver is not insured); } In this program it is important to note that : - The driver will be insured only if one of the conditions enclosed in parentheses evaluates to true. - For the second pair of parentheses to evaluate to true, each condition in the parentheses separated by && must evaluate to true. - Even if one of the conditions in the second parentheses evaluates to false, then the whole of the second parentheses evaluates to false. - The last two of the above arguments apply to third pair of parentheses as well. Thus we can conclude that the && and || are useful in following programming situations: (a) When it is to be tested whether a value falls within a particular range or not. (b) When after testing several conditions the outcome is only one of the two answers. A Word of Caution What will be the output of the following program: main() { inf i; printf(Enter value of i =); scanf(%d,&i); if(i=5) printf(\n You entered 5); else printf(\n You entered something other than 5); } And here is the output of two runs of this program.. Enter value of i= 200 You entered 5

18

Enter value of i = 9999 You entered 5 Surprising? You have entered 200 and 9999, and still you find in either case the output as You entered 5. This is because we have written the condition wrongly. We have used the assignment operator (=) instead of the relational operator (==). As a result of this, the condition gets reduced to if (5), irrespective of what you supply as the value of i. And remember that in C truth is always non-zero, whereas falsity is always zero. Therefore, if (5) always evaluates to true and hence the result. Another common mistake while using the if statement is to write a semicolon (;) after the condition, as shown below: main() { int i; printf(Enter value of i); scanf (%d,&i); if(i== 5) printf(You entered 5); } The ; makes the compiler to interpret the statement as if you have written it in following manner. if(i == 5) printf(You entered 5); Therefore, irrespective of whether the condition evaluates to true or false the printf() is bound to get executed. Remember that the compiler would not point out this as an error, since as far as the syntax is concerned nothing has gone wrong, but the logic has certainly gone away. Moral is, be aware of these pitfalls. The ?: As an alternative to if Consider the following program: main() { int i = 5 ; if(i >= 10) printf(Hello); else printf(Hi); } The same program can be written using the conditional operators as show below. main() { int i = 50; if((i>=10) ? printf(Hello) : printf(Hi)); } You would agree that this program is more compact than the earlier one. If it is so can we not use
19

conditional operators at all places where we use the if-else? No. Because while using the conditional operators after the ? And after the : only one C statement can occur. In practice rarely is this the requirement. Therefore, in serious C programming conditional operators arent as frequently used as the if-else. 6. Switch In real life we are often faced with situations where we are required to make a choice between a number of alternatives rather than only one or two. The control statement which allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since these three keywords go together to make up the control statement. They most often appear as follows: switch (integer expression) { case constant 1: do this; case constant 2: do this ; case constant 3: do this; default: do this; } The expression following the keyword switch is any C expression that will yield an integer value. It could be an integer constant like 1, 2 or 3, or an expression that evaluates to an integer. The keyword case is followed by an integer or a character constant each constant in each case must be different from all the others. The do this lines in the above form of switch represent any valid C statement. What happens when we run a program containing a switch? First, the integer expression following the keyword switch is evaluated. The value it gives is then matched, one by one, against the constant values that follow the case statements. When a match is found, the program executes the statements following the case, and all subsequent case and default statement as well. If no match is found with any of the case statements, only the statements following the default are executed. A few examples will show how this control structure works. Consider the following program: main() { int i = 2; switch(i) { case 1 : printf(I am in case 1 \n); case 2 : printf(I am in case 2 \n); case 3 : printf(I am in case 3 \n); Default :
20

printf(I am in default \n); } } The output of this program would be: I am in case 2 I am in case 3 I am in default Definitely not what we expected. We didnt expect the second and third line in the above output. The program prints cases 2 and 3 and the default case. Well, yes. We said the switch executes the case where a match is found and all the subsequent cases and the default as well. If you think that only case 2 should be executed, it is upto you to get out of the control structure then and there by using a break statement. The following example shows how this is done. Note that there is no need for a break statement after the default, since the control comes to the end anyway. main() { int i = 2; switch(i) { case 1 : printf(I am break ; case 2 : printf(I am break ; case 3 : printf(I am break ; default : printf(I am } }

in case 1 \n); in case 2 \n); in case 3 \n); in default \n);

The output of this program would be: I am case 2 Example The earlier program which used switch may give you the wrong impression that you can use only cases arranged in ascending order, 1,2,3 and default. You can in fact put the cases in any order you ease. Here is an example of scrambled case order:

21

main() { int i = 22 ; switch(i) { case 121 : printf(I am break; case 22 : printf(I am break; case 7 : printf(I am break; default: printf(I am } }

in case 121 \n); in case 22 \n); in case 7\n); in default \n);

The output of this program would be: I am in case 22 Example You are also allowed to use char values in case and switch as shown in the following program: main () { char c=x; switch(c) { case v: printf(I am in case v \n); break; case a: printf(I am in case a \n); break; defualt: printf(I am in default \n); } } The output of this program would be: I am in default 7. Loops in C The programs that we have developed so far used either a sequential or a decision control statement. In the first one, the calculations were carried out in a fixed order, while in the second, an appropriate set of instructions was carried out depending upon the outcome of a condition being tested (or a logical
22

decision being taken). These programs were of limited nature, because when executed, they always performed the same series of actions, in the same way, exactly once. Almost always, if something is worth doing, its worth doing more than once. You can probably think of several examples of this from real life, such as eating a good dinner or going for a movie. Programming is the same; we frequently need to perform an action over and over, often with variations in the details each time. The mechanism which meets this need is the loop, and loops is what we are going to study now. The versatility of the computer lies in its ability to a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control statement. There are three methods by way of which we can repeat a part of a program. They are: (a) Using a while statement. (b) Using a for statement. (c) Using a do-while statement. 8. The While Loop It is often the case in programming that you want to do something a fixed number of times. Perhaps you want to calculate gross salaries of the different persons, or you want to convert temperatures from Centigrade to Fahrenheit it for 15 different cities. The while loop is ideally suited for such cases. Let us look at a simple example, which uses a while loop. Syntax Initialise loop counter; While (test loop counter using a condition) { do this; and this; increment loop counter; } Example 1 /* To generate the series of 1-10 nos main() { int i=1; while(i<=10) { printf(\t%d,i); i++; } */

23

O/P: 1 2 3 4 5 6 7 8 9 10

Example 2 /*Calculation of simple interest for 3 sets of p, n and r */ main() { int p, n, count; float r, si; count = 1; while(count <= 3) { printf(\nEnter values of p, n and r); scanf(%d%d%f, &p, &n, &r); si=p*n*r/100; printf(Simple interest = Rs. %f\n, si); count = count +1; } } And heres is the sample run: Enter values of p, n and r 1000 5 13.5 Simple interest = Rs. 675.000000 Enter values of p, n and r 2000 5 13.5 Simple interest = Rs. 1350,000000 Enter values of p, n and r 3500 5 3.5 Simple interest = Rs. 612.5000000 The program executes all statements after the while 3 times. As a rule the while must test a condition that will eventually become false. Otherwise the loop would be executed forever, indefinitely. Example 3 main() { int i = 1; while(i < = 10) printf(%d, i); }

24

Example This is an infinite loop, since i remain equals to 1 forever. The correct form would be as under: main() { int i = 1; while(i < = 10) { printf(%d, i); i=i+1 ; } } 9. The for Loop Perhaps one reason why few programmers use while is that they are too busy using for, while is probably the most popular looping control statement. The for allows us to specify three things about a loop in a single line : (a) Setting a loop counter to an initial value. (b) Testing the loop counter to determine whether its value has reached the number of repetitions desired. (c) Increasing the value of loop counter each time the program segment within the loop has been executed. The general form of for statement is as under: for (initialise counter; test counter; increment/decrement counter) { do this; and this; } Let us write down the simple interest program using for. Compare this program with the one which we wrote using while. /* Calculation of simple interest for 3 sets of p,n,f,r */ main() { int p, n, count; float r, si ; for (count = 1; count < = 3; count = count +1) { printf(Enter values of p, n and r); scanf (%d %d %f, &p, &n, &r); si=p * n * r/00; printf (Simple Interest = Rs. %f\n, si); } }

25

Let us now write down the program to print number from 1 to 9 using for in different ways: (a) main() { int i ; for(i = 1; i < =10; i = i +1) printf(%d, i); } Note that the initialization, testing and increment of loop counter is done in for statement itself. Instead of i = i +1, the statements i++ or i + =1 can also be used. 10. Nesting of Loops The way if statements can be nested, similarly even whiles and fors can be nested. The c understand how nested loops work, look at the program given below: /*Demonstration of nested loops */ main() { int r, c, sum; for(r=1; r <= 30; r ++) /* outer loop */ { for(c = 1; c <=2; c++) /*inner loop */ { sum = r + c; printf(r = %d c = %d sum = %d\n, r, c, sum); } } } When you run this program you will get the following output: r= 1 c=1 sum = 2 r= 1 c=2 sum = 3 r= 2 c=1 sum = 3 r= 2 c= 2 sum = 4 r= 3 c=1 sum = 4 r= 3 c=2 sum = 5 Here, for each value of r the inner loop is cycled through twice, with the variable c taking values from 1 to 2. The inner loop terminates when the value of c exceeds 2 and the outer loop terminates when the value of r exceeds 3. Having printed each line of output, the cursor is sent to the next line using \n in printf(). As you can see, the body of the outer for loop is indented, and the body of the inner for loop in further indented. These multiple indentations make the program easier to understand. Instead of using two statements one to calculate sum and another to print it out, we can compact this into one single statement by saying : printf(r = %d c = %d sum = %d\n, r, c, r +c);
26

The way for loops have been nested here, similarly, two while loops can also be nested. Not only this, a for loop can occur even within a do-while loop, or a while loop, or a while within a for. 11. Multiple Initialisations in the for Loop The initialisation expression of the for loop can contain more than one statement separated by a comma. For example, for(i = 1, j = 2; j < = 10 ; j++) Multiple statements can also be used in the incrementation expression of for loop; i. e., you can increment (or decrement) two or more variables at the same time. However only one expression is allowed in the test expression, since a single condition must determine when the loop terminates. Use of multiple statements in the initialisation expression also demonstrates why semicolons are used to separate the three expressions in the for loop. If commas had been used, they could not also have been used to separate multiple statements in the initialisation expression, without confusing the compiler. 12. The Odd Loop The loops that we have used to far executed the statements within them a finite number of times. However, in real life programming one comes across a situation when it is not known beforehand how many times the statements in the loop are to be executed. This situation can be programmed as shown below: main() { char another = y int num; while(another== y || another ==Y) { printf(Enter a number); scanf(%d, &num); printf(\n its square = %d\n, num * num); printf(Do you want to enter another number y/n); scanf(%c, &another); } } And here is the sample output. Enter a number 5 Its square = 25 Do you want to enter another number y/n y Enter a number 7 Its square = 49 Do you want to enter another number y/n n In this program the while loop would keep getting executed till the user continues to answer y. The moment he answers n, the loop terminates, since the condition (another==y) fails.
27

13. The do-while Loop The do-while loop like this: do { This; And this; And this; } while (this condition is true); There is a minor difference between the working of while and do-while loops. The difference between them is the place where the condition is tested. The while tests the condition before executing any of the statements within the while loop. As against this the do-while tests the condition after having execution the statement within the loop. This means that do-while would execute its statements at least once, even if the condition fails for the first time itself. The while, one the other hand will not execute its statements if the condition fails for the first time. This difference is illustrated by the following program. Example main() { int i; while(i < 1) { printf(Hello there \n); } } Since in the above program the condition fails for the first time itself the printf() will not get executed at all. main() { int i =4; do { printf(Hello there \n); }while(4 < 1); } In this program the printf() statement would be executed once, since first the body of the loop is executed and then the condition is tested. A part from this peculiarity of the do-while, the while and do-while behave exactly identically. Do-while loops are rarely used in C programs, since there are comparatively fewer occasions when we want to execute a loop at least once on matter what. 14. The Break Statement
28

We often come across situations where we want to jump out of a loop instantly, without waiting to get back to the conditional test. The keyword break allows us to do this. When break is encountered inside any C loop, control automatically passes to the first statement after the loop. A break is usually associated with an if. As an example, lets consider the following problem. Example: Write a program to determine whether a number is prime or not. A prime number is one which is divisible only by 1 or itself. All we have to do the test whether a number is prime or not, is to divide is successively by all numbers from 2 to one less than itself. If remainder of any of these divisions is zero, the number is not a prime. Following is the program to do this. main() { int num,i; printf(Enter a number) ; scanf(%d,&num); i = 2; while(i <= num-1) { if(num % i == 0) { printf(Not a prime number); break; } i++; } if(i == num) printf(Prime number); } In the above program the moment num % i turns out to be zero, (i.e. num is exactly divisible by i) the message Not a prime number is printed and the control breaks out of the while loop. Why does the program require the if statement after the while loop at all? Well, there are two ways the control could have reached outside the while loop: (a) (b) It jumped out because the number proved to be not a prime. The loop came to an end because the value if i became equal to num.

In the second case it means that there was no number between 2 and num 1 that could exactly divide num. That is, num is indeed a prime. If this is true, the program should print out the message Prime number. The keyword break, breaks the control only from the while in which it is placed. Consider the following program which illustrates this fact. main() { int i = 1, j = 1;
29

while(i++<=100) { while(j++<=200) { if(j== 150) break; else printf(%d %d \n, i, j); } } } In this program, when j equals 150 break takes the control outside the inner while only, since it is placed inside the inner while. 16. The continue statement In some programming situations we want to take the control to the beginning of the loop, bypassing the statement inside the loop which have not yet been executed. The keyword continue allows us to do this. When the keyword continue is encountered inside any loop, control automatically passes to the beginning of the loop. A continue is usually associated with an if. As an example, lets consider the following program : main() { int i, j; for(i=1; i <= 2; i++) { for(j = 1; j < = 2; j++) { if(i==j) continue; else printf(%d\t%d\n, i, j); } } } The output of the above program would be. 1 2 2 1

Note that when the value of i equals that of j, the continue statement takes the control to the for loop (inner bypassing rest of the statements pending execution in the for loop (inner). 17. The exit() function exit() is a library function that comes ready-made with the C compiler. Its purpose is to terminate the execution of the program. Very often it is confused with the break statement, though its work is quite different than that of break. Break just terminates the execution of loop (or switch) in which it is written, whereas exit() terminates the execution of the program itself. The following program would make this
30

point clear. main() { int i; for(i = 1; i < 100; i++) { if(i == 3) break; } printf(Out of loop); } In this program the statements within the loop continue to get executed till i is less than 3. The moment i gets a value 3 the condition in if gets satisfied. As a result the break forces the termination of the loop and takes the control to the first statement after the loop. Since this statement is printf(), Out of loop gets printed. Suppose in place of break the function exit() is used, the moment the condition is satisfied exit() would terminate the execution of the program without executing the printf(). 18. The goto statement Avoid goto statements! They make a C Programmers life miserable. There is seldom a legitimate reason for using goto, and its use is one of the reasons that programs become unreliable, unreadable, and hard to debug. And yet many programmers (especially those using Basic) find goto seductive. In a difficult programming situation it seems so easy to use a goto to take the control where you want to. However, almost always, there is a more elegant way of writing the same program using if, for while and switch. These constructs are far more logical and easy to understand. A goto statement can cause program control to end up almost anywhere in the program, for reasons that are often hard to unravel. Trust me, with good programming skills, goto can always be avoided. This is the first and last time that we are going to use here . Consider the following program. main() { int goals; printf(Enter the number of goals scored against India); scanf(%d, &goals); if(goals <= 5) goto sos; else { printf(About time soccer players learnt C\n) printf(and said goodbye! Adieu! To soccer); exit(); /*terminates program execution */ }
31

sos: printf(To err is human!); } And here are two sample runs of the program. Enter the number of goals scored against India 3 To err is human! Enter the number of goals scored against India 7 About time soccer players learnt C and said goodbye! Adieu! To soccer A few remarks about the program would make the things clearer. If the condition is satisfied the goto statement transfers control to the label sos, causing printf() following sos to be executed. The label can be on a separate line or on the same line as the statement following it, as in, sos: printf(To err is human!); Any number of gotos can take the control to the same label. The exit() function is a standard library function which terminates the execution of the program. It is necessary to use this function since we dont want the statement.

printf (To err is human!); To get executed after execution of the else block. The big problem with gotos is that when we do use them we can never be sure how we got to a certain point in our code. They obscure the flow of control., So as far as possible skip them. You can always get the job done without them. The only programming situation in favour of using goto is when we want to take the control out of the loop which is contained in several other loops. The following program illustrates this.

main() { int, i, j, k; for(i=1; i <= 3; i++) { for(j=1; j <= 3; j++) { for(k=1; k <= 3; k++) { if(i == 3 && j== 3 && k == 3) goto out; else printf(%d %d %d\n, i, j, k); } } } out: printf(Out of the loop at last);
32

} Go through the program carefully and find out how it works. Also write down the same program without using goto.

33

Exercise [A] What will be the output of the following programs: (1) main() { int a = 600, b = 400, c; if(!a >=400) b=300; c=200; printf(b=%d c=%d, b, c); } (2) main() { if(!3.14) printf(I have robbed and killed); else printf(Until my evil purse was filled); } (3) main() { float a = 12.25, b = 13.65; if(a=b) printf(a and b are equal); else printf(a and b are not equal); } (4) main() { int i = 10, j = 40; if ((j-i) %10) printf(man sees your actions..); else printf(god sees your motives..); } (5) main() { flot a = 0.7; if(a < 0.7) printf(Stoned); else printf(Avenged);}
34

(6) main() { int x = 10, y = 20; if(!(!x) &&x) printf(x=%d, x); else printf(y = %d, y); } (7) main() { float a = 0.5, b = 0.9; if(a && b > 0.9 printf(Idleness is a virute); else printf(..so is stupidity!); } (8) main() { int x = 100; if(!x) printf(x-%d, !x); else printf(x = %d, x); } (9) main() { int i; printf(Enter any number); scanf(%d, &i); switch(i) { case 1: printf(Do); case 2: printf(Re); case 3: printf(Me; case default: printf(Fa So La Ti Do); } }

35

(10) main() { int k = -2, j = 4; switch (k/=j/k) { default: printf(All are same!\n); case 0: printf(Happy birthday\n); case 1: printf(A punch on the mouth\n) case 2: printf(A kick in the back\n); } } (11) main() { char ch = E; switch (ch) { case (ch>=65 && ch < 90); printf (Capital Letter); break; case (ch>=97 && ch<122); printf(Small case Letter); break; case (ch>=48 && ch <=57); printf(Digit); break; default: printf(Any other character); } } (12) main() { int i, j; for (j=1; j < = 10; j++) { for (i=1; i < = 10; i++) { if(j < 10) goto out; } printf(Murphys first law\n); printf(If the price of the PC is a dream\n); printf(Then the service would be a nightmare);
36

} out: printf(Dream about a nightmare); } (13) main() { int i, j, k; for(j = 1; j < = 4; j++) { if (j * j == 16) goto secretplace; } for (i = 1; i <=5; i++) { k = i * i; j = k+2; secretplace: printf(Murphys second law\n); printf(Good computers are always priced\n); printf(Just beyond your budget\n); } } (14) main() { char j = 1; while (j < = 255) { printf(%d\n, j); j = j +1; } } (15) main() { int j = 1; while(j<=255) printf(%d\n, ++j); } (16) main() { int a ; for (a = 1; a < = 32767; a++) printf(%d, a);
37

} (17) main() { int i; for(i=1;i<=5;i++) printf (%d, i)); } (18) main() { int i = 1; for (;i++;) printf(%d, i); } (19) main() { int a = 5; do { printf(%d\n, a); a=-1; } while(a > 0); } [B] Attempt the following:

(1) Here is an ecological simulation of wolf and rabbit populations. Rabbits eat grass. Wolves eat rabbits. There is plenty of grass, so wolves are the only obstacle to the rabbit population increase. The wolf population increases with the population of rabbits. The day-by-day changes in the rabbit population R and the wolf population W can be expressed by the following furmulae: R(tommorrow) = (1 + a).R(today) c.R(today).W(today) W(tommorrow) = (1- b).W(today)+c.d.R(today).W(today) a = 0.01 = fractional increase in rabbit population without threat from wolves (0.01 means 1% increase) b = 0.005 fractional decrease in wolf population without rabbit to eat c = 0.00001 = likelihood that a wolf will encounter and eat a rabbit d = 0.01 = fractional increase in wolf population attributed to a devoured rabbit. Assure that initially there are 10,000 rabbits and 1000 wolves. Write a program to calculate populations of rabbits and wolves over a 1000-day period. Have the program print the populations every 25 days. See
38

what happens when you start with 500 wolves instead of 1000. Try starting with 2000 wovles too. (2) Super-Duper Micros currently sells 100 Super-Dupers per month at a profit of Rs. 500/- per Super-Duper. They have a fixed operating cost of Rs. 10,000/- that does not depend on the volume of sales. They currently spend Rs. 1000/= per month on advertising. A marketing consultant advised them that if they double the amount spent on advertising, sales will increase by 20%. Write a program that begins with the companys current status, and successively doubles the amount spend on advertising until the net profit begins to decline. Have the program print the number of Super-Duper sales, the advertinsing budget, and the net profit just before the profit begins to decline. (3) The equation x2 + y2 = r2 represents a circle with centre at origin and radius r. Write a program that reads r from the keyboard and prints the number of points with integer coordinates that lie within the circle. (4) Write a program that, for all positive integers i, j, k, and I from 1 through 1000, finds and prints all combinations of i, j, k, and I such that i + j + k = 1 and i < j < k < l. (5) Write a program which finds four digit perfect squares where the number represented by the first two digits and the number represented by the last two digits are also perfect squares. (6) Write a program which finds a four digit number AABB which is a perfect square. A and B represent different digits. (7) If number 972 is entered through the keyboard, your program should print Nine Seven Two. Write the program such that it does this for any positive integer. (8) A positive integer is entered through the keyboard. Alongwith it the base of the numbering system in which you want to convert this number is entered. Write a program to display the number entered, the base, and the converted number. For example, if the input is 64 2 then output should be 64 2 1000000. Similarly, if the input is 64, 16, then the output should be 64 16 40.

39

CHAPTER 5 ARRAYS AND STRINGS ARRAYS Array is the set of similar data elements stored under one name. These similar elements could be all int, all float or all chars etc. We can store more then one element in array after defining the limit of array. For understanding the array properly, let us consider the following examples Program Suppose, If we want to calculate the average of 10 numbers through simple variable program; First we assume 10 variables to store 10 numbers. And then we will calculate the average like this: main() { int a,b,c,d,e,f,g,h,i,j,avg; clrscr(); printf(Enter the no:); scanf(%d,&a); printf(Enter the no:); scanf(%d,&b); printf(Enter the no:); scanf(%d,&c); printf(Enter the no:); scanf(%d,&d); printf(Enter the no:); scanf(%d,&e); printf(Enter the no:); scanf(%d,&f); printf(Enter the no:); scanf(%d,&g); printf(Enter the no:); scanf(%d,&h); printf(Enter the no:); scanf(%d,&i); printf(Enter the no:); scanf(%d,&j); avg=(a+b+c+d+e+f+g+h+i+j)/10; printf(The average of 100 No = %d,avg); getch(); } Through the above method, calculating the average of 10 numbers is a very lengthy procedure. But it is very easy to calculate the average of 10 numbers using array, like this:

40

main() { int a[10],avg,sum=0; clrscr(); for(i=0;i<=9;i++) { printf(Enter the no:); scanf(%d,&a[i]); sum=sum+a[i]; } avg=sum/10; printf(The average of 10 No: = %d,avg); getch(); } Array Declaration We can declare/ initialise the array like this: int a[10]; In this declaration, the number 10 tells that how many elements of the type int will be stored in an array. This number is often called the dimension of the array. The bracket ( [ ] ) tells the compiler that we are dealing with an array. int float a[5]={2,3,6,8,6}; b[4]={2.5, 5.66, 5.7, 4.6};

The above declaration is called the constants declaration in an array. Array elements in memory Let us consider the following declaration: int a[8]; We know that integers occupy the 2 bytes in the memory, It means that the above 8 integers occupy the memory 16 bytes long. The memory arrangement of above array is shown in fig.: a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] 12 4 15 77 65 11 8 69 4000 4002 4004 4006 4008 4010 4012 4014 a[0], a[1].................. are the array variable name. 4000, 4002, 4006..... are the memory address. 12, 4, 15,...................are the values stored in array. Note: Memory addresses can be changed according to computers memory model. Entering and reading the data from an array
41

Here is the section of code that places data in to an array: for(i=0;i<9;i++) /* loop for entering the elements in array */ { printf((\n Enter marks :); scanf((%d,&a[i]); } for(i=0;i<9;i++) /* loop for reading the elements in array */ { printf((\n %d,,a[i]); } Two Dimensional array So far we have looked at array with one dimension. It is possible for us to have two or more dimensions. The two dimensional array is also called a matrix or a table. We can declare/ initialise the two dimensional array like this: int a[4][3]; In this declaration, [4][3] tells that we can store 12 int elements in an array. int a[4][3]={ {2,3,5}, {6,8,6}, {4,9,6}, {2,3,8}, }

Above declaration is called the constants declaration in array.

42

Exercise Q1. Describe the output generated by each of the following programs: (a) #include<stdio.h> main() { int t[5]={1,4,5,7,8},i; for(i=0;i<5;i++) { printf(%d\n,a[i]); } getch(); } (b) #include<stdio.h> #define ROW 3 #define COLUMNS 4 main() { int z[ROW][COLUMNS]; for(i=0;i<ROW;i++) for(j=0;j<COLUMNS;j++) { printf(Please enter the no:); scanf(%d,&z[i][j]); } for(i=0;i<ROW;i++) for(j=0;j<COLUMNS;j++) { printf(%d\t,z[i][j]); } getch(); } (d) #include<stdio.h> main() { int b[5],t[5]={1,4,5,7,8},i; for(i=0;i<5;i++) { if((t[i]%2)==0) b[i]=t[i]); printf(%d\n,b[i]); } getch(); }

Q2. Write the program for printing the following 4x3 matrix through array : 3 4 1 2 5 7 3 6 9 3 9 2

Q3. Input the 10 numbers in array through key board, and arrange these numbers in ascending order. Q4. Input five students name and their marks, through key board and display the list of name and marks in the following order: Name Naveen Tanuj Anurag Preeti Marks 80 69 70 75

Q5. Write a program for addition of two matrices. Q6. Write a program for multiplication of two matrices.

43

STRINGS A string is the collection of any number of characters by default ending with NULL (\0) character. String declaration We can declare/ initialise the string like this: char a[10]; In this declaration, the number 10 tells how many character will be stored in the array named as a. This number is often called the dimension of the array. The bracket ( [ ] ) tells the compiler that we are dealing with an array. Char a[5]={t,a,n,u,j}; The above declaration is called the constants declaration in character array. Array elements in memory Let us consider the following declaration: char a[5]; We know that a character occupies 1 byte in the memory. It means 8 characters occupy 8 bytes in the memory. The memory arrangement of the above array is shown in fig.: a[0] a[1] a[2] a[3] a[4] a[5] T A N U J \0 4001 4002 4003 4004 4005 4006 a[0], a[1].................. are the array variable name. 4001, 4002, 4006 ..... are the memory address. T, A,.................... are the characters stored in an array. Note: Memory address can be changed according to computers memory model. Input /Output of strings Reading words The familiar input function scanf() can be used with %s format specifications to read in a string of character. Example: char address[15]; scanf(%s,address);

44

Writing string to screen We have used extensively the printf() function with %s format to print the string. The format %s can be used to display an array of characters that is terminated by the null character. For example, the statement printf(%s,address); can be used to display the entire contents of the array. We can also use the following functions for input and output the strings gets(char var) : Inputs multiple characters from the keyboard. It terminates the string by \n. puts(char var ) : It sends a character on screen. Let us discuss following examples Example 1. #include<stdio.h> #include<string.h> main() { char name[20]; printf(Please Enter your good name:); gets(name); printf(Your name inputed as below:); puts(name); getch(); } Explanation : In above program gets functions will input name of the user from the keyboard and puts will display the name of the user on the screen. Example 2: Calculate the length of given string. #include<stdio.h> #include<string.h> main() { char s[10]; int i,n=0; printf(Enter any string:); gets(s); for(i=0;s[i]!=\0;i++) { n++; } printf(The string length =%d,n); getch();} General functions of string
45

strlen(char var) :- count the total number of characters in the given string. Example: strlen(anurag) produces the output as 6

strcmp(string1,string2) :- compares two strings and gives 0 (zero) if strings are equal. Example: strcmp(Agra,Agra) strcmp(Agra,Bombay) strcmp(Bombay,Agra) produces the output as 0 produces the output as -1 produces the output as +1

strcat(string1,string2) :- concatenates both the strings. Example: strcat(micro,soft) produces the output as microsoft

strcpy(string1,string2) :- copies string2 in to string1. Example: strcpy(tanuj, chauhan) produces the output as chauhan

46

Exercise Q 1. Write the program to print the reverse of input string. Q 2. Input any sentence through keyboard and count the blank spaces, and number of words in the sentence. Q3. Input any string and find out whether the string is palindrome or not. Q4. Count how many vowels are there in the string. Q5. Print the following pyramid: C CO COM COMP COMPU COMPUT COMPUTE COMPUTER

47

CHAPTER 6 FUNCTIONS Function definition A complex problem may be decomposed into the smaller or manageable parts or modules known as functions. Or A function is a self-contained block of code that performs a particular task. The inner details of the operations of functions are invisible to rest of the program. A function can have any number of executable statements. Or A function is a macro, which is assigned several instructions that are to be executed. Classification of functions Functions can be classified into two categories, namely library functions and user defined functions. The main() is an example of user-defined function. printf() and scanf() belongs to the category of library functions. FUNCTION NAME Function must follow the same rules of formation as the other variables in C language. Additional care must be taken to avoid duplicating library routine names or operating commands. Syntax function name argument declaration { local variable declaration; statements; statements; return(expression) } E.g. power(x,n) { float a; int n; statements; statements; return; } Category of functions

48

(i) (ii) (iii) (iv)

Function with no argument and no return values Function with argument and no return values Function with no argument and return values Function with argument and return values

Local and Global variables Local variables are accessible only inside defined function and get memory freed as soon as function gets over. Global variables are accessible any where in side program and get memory freed as soon as program gets over. Ex 1. /*Function with no argument and no return values #include<stdio.h> main() { mss(); /* getch(); } */

function calling

*/

mss() { printf(\nThis is my first program using function..); } Ex 2. /* Function with argument and no return values */

#include<stdio.h> main() { int a,b; printf(\nEnter value of a : ); scanf(%d,&a); printf(\nEnter value of b : ); scanf(%d,&b); sum(a,b); /* function calling */ getch(); } sum(int x,int y) { int c; c=x+y; printf(\n Addition of %d + %d = %d,x,y,c); } Ex 3.

49

/*

Function with no argument and return values

*/

#include<stdio.h> main() { int add; add=sum(); /* function calling printf(\n Addition = %d,add); getch(); } sum() { int a,b; printf(\nEnter value of a : ); scanf(%d,&a); printf(\nEnter value of b : ); scanf(%d,&b); return(a+b); } Ex 4: /* Function with argument and return values

*/

*/

#include<stdio.h> main() { int x,y; int add; printf(\nEnter value of x : ); x=inputvalue(); /* function calling without argument printf(\nEnter value of y : ); y=inputvalue(); /* function calling without argument add=sum(x,y); /* function calling with argument */ printf(\n Addition = %d,add); getch(); } sum(int a, int b) { return(a+b); } inputvalue() { int k; scanf(%d,&k); return(k); }

*/ */

50

Nesting of Functions We can perform nested function calling, in which one function can call another function and similarly second can call third function. Ex 5: /* Example of nesting in function */ #include<stdio.h> main() { int a,b; printf(\n Enter value of a : ); scanf(%d,&a); printf(\n Enter value of b : ); scanf(%d,&b); analysis(a,b); } analysis(int x, int y) { if (a>0) status=1; else status=2; mss(status); } mss(int status) { if (status==1) printf(\nInputed value is positive); else printf(\nInputed value is negative); } Recursion Like other high level languages, C permits recursion where a called function can call itself. For example the main() can call it self. /* Example of recursion */ #include<stdio.h> main() { printf(\nMain function calling itself..); main();} Here in the above example it will produce following output in each turn of calling

51

Main function calling itself.. Main function calling itself.. Main function calling itself.. Main function calling itself.. . Another useful example of recursion is calculating factorial of a given value: #include<stdio.h> main() { int num; long int fact; printf(\nEnter a number : ); scanf(%d,&num); fact=factorial(num); printf(\nfactorial of %d = %ld,num,fact); } factorial(int n) { long int f=1; if(n==1) return(1); else f=n*factorial(n-1); /*function factorial is called itself*/ return(f); } Passing address as argument to a function #include<stdio.h> main() { int a,b; a=10; b=20; printf(\nValues before swaping\n a= %d, b = %d,a,b); swap(&a,&b); /* passing addresses of a and b */ printf(\nValues after swaping\n a= %d, b = %d,a,b); } swap(int *x ,int *y) /* x and y are pointer variables which will hold address of a and b */ { int k; k=*x; *x=*y; *y=k; }

52

A function can be defined in the header that can be included in main() function using #include file.h or file.c. Function definition in a file File name : userfun.c sum(int a, int b) { int c; c=a+b; return(c); } swap(int *x ,int *y) /* x and y are pointer variables which will hold the address of a and b */ { int k; k=*x; *x=*y; *y=k; } File name : prog.c #include <stdio.h> #include userfun.c main() { int t,n; printf(\nEnter value of scanf(%d,&t); printf(\nEnter value of scanf(%d,&n); printf(\nAddition of %d printf(\nBefore swaping swap(&t,&n); printf(\nAfter swaping getch(); }

t : ); n : ); + %d = %d,sum(t,n)); t = %d, n = %d,t,n); t = %d, n = %d,t,n);

53

Exercise 1. 2. 3. 4. Write a function for drawing a dotted line. Write a function for finding that given number is prime or composite. Write a function which receives a float and an integer from main(), finds the sum of these two and returns the values which is printed through main(). Write a program which will calculate the sum of digit of input number. Assume number should be of 5 digits. return(m); } Prg3 #include<stdio.h> main() { int ar; float r=2.0; ar=ac(r); printf(\nArea = %f,ar); } ac(float r) { float x; x=3.14*r*r); printf(\nx= %f \n,x); return(x); }

Observe the following programs Prg1 #include <stdio.h> main() { int k=35,z; z=fun(k); printf(\nz= %d ,z); } fun(int m) { ++m; return(m=fun1(++m)); } fun1(int n) { m++; } Prg2 #include<stdio.h> main() { void mss(); int a; printf(a before call %d\n,a); a=mss(); printf(\n a after call %d,a); } void mss() { printf(\nOnly he will who is computerate); }

= =

survive

54

CHAPTER 7 POINTERS The computers memory is a sequential collection of storage cells. Each cell, commonly known as byte, has a number called address associated with it. Typically, the addresses are numbered consecutively, starting from zero. The last address depends on the memory size. A computer system having 64 K memory will have its last address as 65,535. Why we should use pointers 1. 2. 3. 4. 5. Saving of data storage space in memory while using pointer array to character strings. They increase execution speed. They are more efficient in handling data tables. We can access variable that is defined outside the function. They are helpful managing length and complexity of program

Whenever we declare a variable, system allocates space somewhere in the memory, an appropriate location to hold the value of the variable. Since, every byte has a unique address number, the location will have its own address number. Consider the following declaration: int a = 10; Above declaration will instruct the compiler to: 1. Reserve space in memory to hold the integer value. 2. Associate the name a with this memory location. 3. Store the value 10 at this location. We may represent as location in the memory as given below: a
10

Location name Value at location Address

3240

We see that the computer has selected memory location 3240 as the place to store the value 10. The location number 3240 is not a number to be relied upon, because some other time the computer may choose a different location for storing same value. The important point is, as address in memory is a number. The & and * operators Like other variables in C, pointers are to be declared for their type. Pointer variables contain addresses of variable that are to be pointed. The syntax for declaring pointer variable is as follows: data type *pnt_name; Above declaration reveals three things about pnt_name to compiler: 1. The asterisk (*) tells pnt_name is pointer variable. 2. pnt_name needs storage space in memory.
55

3. pnt_name points to a variable of type data type. For example: int *a; The above declaration specifies a as a pointer variable that points to an integer data type. Remember that the type int refers to the data type of the variable being pointed to by a and not the type of the value of the pointer. Once pointer variable has been declared, it can be made to point to a variable using an assignment statement such as x=&roll_no; Which causes x to point to roll_no. That is x now contains of roll_no. This is known as pointer initialization. Before a pointer is initialized, it should not be used. Example #include<stdio.h> main() { int a=10; printf(\nAddress of a = %d\n,&a); printf((Value of a = %d\n,a); } The output of the above program would be: Address of a = 3240 Value of a = 10 Look at the first printf() statement carefully. & used in this statement is Cs address of operator. The expression &a returns the address of the variable a, which in this case happens to be 3240. We have been using this & all the time in the scanf() statement. Observe the following program: main() { int a = 2; printf(Address of a = %d\n,&a); printf(Value of a = %d\n,a); printf(Value of a = %d\n,*(&a)); }

56

O/P: Address of a = 3240 Value of a = 2; Value of a = 2; Note that printing the value of *(&a) is same as printing the value of a; Pointers and arrays When we declare an array, compiler allocates a base address and reserves given number of spaces in contiguous memory location. The base address is the location of first element of array. Observe the following example: static int a[3]={10,20,30}; Suppose the base address of a is 3000 and assuming that two bytes, the three elements will be stored in a following way a[0] 10 3000 a[1] 20 3002 a[2] 30 3004 Element Value Address

The name a is declared as a constant pointer to the first element, a[0] and therefore the value of a is 3000, where a[0] is stored. a= &a[0]=300 If we declare b as an integer pointer, then we can write following statement b=a; Above assignment is equivalent to: b=&a[0]; b=&a[0]=3000 b+1= &a[1]= 3002 b+1=&a[2]= 3004 Observe the following example: #include <stdio.h> main() { int arr[10]={1,2,3,4,5,6,7,8,9,10},*x; x=a; for(i=0;i<=9;i++) {
57

printf(\n %d ,*x); x++; } getch(); } Above program will display ten elements of array named as arr. x is defined as integer pointer. x=arr is defined that x is a pointer to arr. x++ will increment in next address of next element stored in arr *x will display value at current address of arr. Same output will be shown on screen by following program: #include <stdio.h> main() { int arr[10]={1,2,3,4,5,6,7,8,9,10}; for(i=0;i<=9;i++) printf(\n %d ,a[i]); getch(); } Pointers and functions We can pass address of the variables as argument to the function #include <stdio.h> main() { int a,b; printf(\nEnter value of a : ); scanf(%d,&a); printf(\nEnter value of b : ); scanf(%d,&b); printf(\nValues before interchange : %d, %d,a,b); change(&a,&b); printf(\nValues after interchange : %d, %d,a,b); } change(int *x ,int *y) { int k; k=*x; *x=*y; *y=k; } /* x and y are pointer variables which will hold address of a and b */

58

Exercise Observe the output of following programs Prg1. #include<stdio.h> main() { static char arr[]=HARDWAR char *p= HARDWAR; printf(\n %d %d,sizeof(arr),sizeof(p)); } Prg2. #include<stdio.h> main() { static chat arr[]=My name is Robert; int a; char *x; for(x=arr,a=0,x+a<=arr+strlen(arr);x++,a++) printf(%c,*(x+a)); } Prg3. #include<stdio.h> main() { static int x[5]={1,2,3,4,5}; int a; change(x); for(a=4;a=0,a--) printf(%d,x[a]); } change(int *t) { int m; for(m=0;m<=4;m++) { *t=*t+1; t++; } }

59

CHAPTER 8 STRUCTURES A structure gathers together, different type of data under one name that comprises a given identity. As we know that one variable can hold only one value, while variable of array type can hold multiple values of same type but structure variable can hold multiple values of different type. Declaring structure struct <struct name> { data type 1; data type 2; data type 3; }; Once the new structure data type has been defined one or more variables can be declared to be of that type. For example: struct employee v1,v2,v3,..; (Here employee is the structure name and v1,v2,v3,.. are the variables of said structure) Let us consider the following example to explain structure: #include <stdio.h> main() { struct employee { char name[20]; int age; float salary; char address [20]; }; struct employee e1,e2; /* e1,e2 are variable of employee printf(\nEnter name : ); scanf(%s,&e1.name); printf(Age : ); scanf(%d,&e1.age); printf(Address : ); scanf(%s,&e1.address); printf(Salary : ); scanf(%f,&e1.salary); printf(\n\nNow the entry for second variable : ); */

60

printf(\nEnter name : ); scanf(%s,&e2.name); printf(Age : ); scanf(%d,&e2.age); printf(Address : ); scanf(%s,&e2.address); printf(Salary : ); scanf(%f,&e2.salary); printf(\n\nOutput of input variables : ); printf(\nValues of variable (e1)); printf(\n name : %s,e1.name); printf(\nAge : %d,e1.age); printf(\nAddress : %s,e1.address); printf(\nSalary : %f,e1.salary); printf(\nValues of variable (e2)); printf(\nName : %s,e2.name); printf(\nAge : %d,e2.age); printf(\nAddress : %s,e2.address); printf(\nSalary : %f,e2.salary); } Assigning values in structure struct values { int a; float b; }x = {10,20.23}; values of x can be printed as follows: printf(\n %d, %f ,x.a,x.b); O/P: 10, 20.23 Array of structures If we require to input more and more structured values to the variable, then we will define variable of array type. Observe the following example: struct book { char name[10]; float price; int page; };

61

struct book c[100]; int k; for(k=0;k<=99;k++) { printf(\nEnter name, price, pages : ); scanf(%s %f %d,&c[i].name,&c[i].price,&c[i].page); } for(k=0;k<=99;k++) printf(\n name : %s\t price : %f\t pages : %d,c[i].name,c[i].price,c[i].page); } Nesting of structure #include<stdio.h> main() { struct student { char name[10]; int marks; struct date { int dd; int mm; int yyyy; }; struct date d_o_b; }; struct student stu[50]; for(i=0;i<=49;i++) { printf(Enter the student name:); scanf(%s,&stu[i].name); printf(Enter the student marks:); scanf(%d,&stu[i].marks); printf(Enter the student birth date:); scanf(%d,&stu[i].date.dd); printf(Enter the student birth month:); scanf(%d,&stu[i].date.mm); printf(Enter the student birth year:); scanf(%d,&stu[i].date.yyyy); } for(i=0;i<=49;i++) { printf(The student name :%s,stu[i].name);
62

printf(The printf(The printf(The printf(The getch(); } }

student student student student

marks:%d,stu[i].marks); birth date:%d,stu[i].date.dd); birth month:%d,stu[i].date.mm); birth year:%d,stu[i].date.yyyy);

Copying the contents of one variable to another #include<stdio.h> main() { struct book { char name[10]; float price; int page; }; struct book c1,c2; printf(\nEnter name, price, pages : ); scanf(%s %f %d,&c1.name,&c1.price,&c1.page); printf(\n name : %s\t price : %f\t pages : %d,c1.name,c1.price,c1.page); getch(); c2=c1; /* passing the structure values of c1 into c2 */ printf(\n name : %s\t price : %f\t pages : %d,c2.name,c2.price,c2.page); getch(); } Passing structure elements to function #include<stdio.h> main() { struct book { char name[30]; char author[30]; int refno; }; static struct book b1={Let us Learn C Language,SADNT,100}; display(b1.name,b1.author,b1.refno); } display(char *s, char *t, int n)
63

{ printf(%s\n%s\n%d,s,t,n); } O/P: Let us Learn C Language SADNT 100 Exercise 1- Define a structure having the following fields: Item code, Item name, Quantity, Price. Enter the records for 10 products and display the information. 2- Define a structure book with the following field name: title, publisher, page, price. Take three variables and copy the input value of variable one into two and three. Display the overall information too.

64

CHAPTER 9 FILE HANDLING IN C File Definition It is a collection of information of similar object. It is necessary to have files since this is a more flexible approach where data can be stored on the disk and read whenever necessary, without destroying the previous data. A file is a place where we can store data for future reference. Like other languages, C supports various functions for file management, which includes: Naming a file Opening a file Reading data file Writing data into file Closing file

Following are the functions which are used in C for I/O in files. These functions are defined in Cs standard I/O library. Name of Function fopen() fclose() getc() putc() fprintf() fscanf() getw() putw() fseek() ftell() rewind() fread() fwrite() getchar() putchar() Operations performed by function Creates a new data file/open an existing file Closes existing file Reads character from file/keyboard Writes a character to file/screen Writes stream into file Reads stream from file Reads an integer from file Writes an integer in to file Sets pointer on specific position It returns current position of pointer in file Sets pointer on beginning in file Reads the stream from file Writes the stream into file Gets charcter from stdin(standard input unit) Outputs character on stdout(standard output unit)

The modes for operation are give below: Mode w r a Operation Searches file. If file exists, its contents are overwittten. If the specified file doesnt exist, a new file is created. Returns NULL if unable to open file. Searches file. If file exists, loads it into memory and sets up a pointer which points to the first characters in it. If the specified file doesnt exist, It returns NULL if unable to open file. Searches file. If file exists, loads it into memory and sets up a pointer which points to the
65

w+ r+

a+

first characters in it. If the specified file doesnt exist, a new file created.Returns NULL if unable to open file. Searches file. If file exists, its contents are destroy. If the specified file doesnt exist, a new file is created. Returns NULL if unable to open file. Operations possible-writing new contents, reading them back and modifying existing contents of the file. Searches file. If file exists, loads it into memory and sets up a pointer which points to the first characters in it. If the specified file doesnt exist, It returns NULL if unable to open file. Operations possible-reading existing contents, writing new contents, modifying existing contents of the file. Searches file. If file exists, loads it into memory and sets up a pointer which points to the first characters in it. If the specified file doesnt exist, a new file created.Returns NULL if unable to open file. Operations possible- reading existing contents, appending new contents to end of file. Cannot modify existing contents of the file.

Creation of file If we want to store a stream into a secondary memory (Disk), we must specify certain things about a file to the Operating system. They include: File name Data structure Operation Syntax FILE *fp; fp=fopen(filename.ext,mode); Reading from a file To read the files stream from memory there exists a standard library function called getc(). We use this function as follows: c=getc(fp); Syntax FILE *fp; fp=fopen(filename.ext,r); Closing existed file If we need to close the opened file after operation we use fclose() function. Syntax fclose(fp); fclose() will close the specified file for operation. Let us consinder examples on different operations. First we are going to handle unformatted data using different operations.
66

Writing data into file #include<stdio.h> main() { FILE *fp; int ch; fp=fopen(text.dat,w); while((ch=getchar())!=EOF) putc(ch,fp); fclose(fp); } while loop will be continued till pressing ^Z (for EOF). O/P: This is line 1 This is line 2 This is line 3 Reading data from file #include<stdio.h> main() { FILE *fp; int ch; fp=fopen(text.dat,r); while((ch=getc(fp))!=EOF) putc(ch,stdout); /* */ fclose(fp); } O/P: This is line 1 This is line 2 This is line 3 Append data into old file #include<stdio.h> main() { FILE *fp; int ch; fp=fopen(text.dat,a); while((ch=getc(stdin))!=EOF) stdin(Keyboard)*/ putc(ch,fp);

writes character on to stdout(screen)

/* reads a character from /* writes a character into file


67

*/ fclose(fp); } O/P: This is line 4 This is line 5 The contents can be viewed by reading a file. I/O of formatted data in file In previous examples we have handled characters and strings. Now, we are going for I/O of formatted data into file. Writing data into specified file #include<stdio.h> main() { FILE *fp; char name[20]; int age; int roll_no; float fee; char ch=y; fp=fopen(stud.dat,w); while(ch==y || ch ==Y) { printf(\nEnter roll number : ); scanf(%d,&roll_no); printf(\nName : ); gets(name); printf(Age : ); scanf(%d,&age); printf(Fee : ); scanf(%f,&fee); fprintf(fp,%d %s %d %f\n,&roll_no,name,&age,&fee); printf(\nDo you want more entry [y/n] : ); fflush(stdin); /* To clear buffer of keyboard memory */ ch=getche(); /* Inputs character to ch */ } fclose(fp); }

68

O/P: Enter roll number : 123 Name : Sunil Kapoor Age : 23 Fee : 500.00 Do you want more entry [y/n] : n Reading a specified file #include<stdio.h> main() { FILE *fp; char name[20]; int age; int roll_no; float fee; fp=fopen(stud.dat,r); while(fscanf(fp,%d%s%d%f,&roll_no,name,&age,&fee)!= EOF) { printf(\n Roll number : %d,roll_no); printf(\nName : %s,name); printf(Age : %d,age); printf(Fee : %f,fee); } fclose(fp); } O/P: Roll number Name Age Fee : 123 : Sunil Kapoor : 23 : 500.00

Appending data in to specified file #include<stdio.h> main() { FILE *fp; char name[20]; int age; int roll_no; float fee; char ch=y; fp=fopen(stud.dat,a); while(ch==y || ch ==Y) {
69

printf(\nEnter roll number : ); scanf(%d,&roll_no); printf(\nName : ); gets(name); printf(Age : ); scanf(%d,&age); printf(Fee : ); scanf(%f,&fee); fprintf(fp,%d %s %d %f\n,&roll_no,name,&age,&fee); printf(\nDo you want more entry [y/n] : ); fflush(stdin); /* To clear buffer of keyboard memory */ ch=getche(); /* Inputs character to ch */ } fclose(fp); } O/P: Enter roll number : 12 Name : Amit Kumar Age : 13 Fee : 550.00 Do you want more entry [y/n] : n Modified records may be displayed by reading the file. Binary file vs Text file There are three reasons where text and binary files are different: The handling of new lines The representation of EOF The storage of numbers Let us consider the following menu driven example which shows DBMS concept. In following example we will perform following operations on students records: Adds new records Modify existed record Listing of records Delete un-required record Data structure of students record as follows: Roll number Name of student Course code Fee Age Duration

70

#include<stdio.h> main() { struct student { int roll_no, age; char c_code[5], name[20], dur[10]; float fee; }; FILE int char Struct int *fp1,*fp2; ch; ans; student s; n_roll_no; /* wb+ used for opening file in

fp1=fopen(SMTCI.DAT,rb+); binary mode

for O/P */ If(fp1==NULL) { fp1=fopen(SMTCI.DAT,wb+); if(fp1==NULL) { printf(\nUnable to open SMTCI.DAT); exit(0); } } while(1) { printf(\n\t\tSMT Computer Institute); printf(\n\t\tStudents Record Tracker); printf(\n\t\t---------------------------------); printf(\n\n1. Adds new records); printf(\n 2. Listing of records); printf(\n 3. Modify records); printf(\n 4. Delete record); printf(\n 5. EXIT); printf(\n\nEnter your choice : ); scanf(%d,&ch); switch(ch) { case 1: fseek(fp1,0,SEEK_END); ans=Y; while(ans==Y || ans==y) { printf(\nEnter roll number : ); scanf(%d,&s.roll_no); printf(Name : );
71

scanf(%s,s.name); printf(Age : ); scanf(%d,&s.age); printf(Course code : ); scanf(%s,s.c_code); printf(Fee : ); scanf(%f,&s.fee); printf(Duration of course : ); scanf(%s,s.dur); fwrite(&s,sizeof(s),1,fp1); printf(\nAdd more information [y/n] ); fflush(stdin); ans=getche(); } break; case 2 : rewind(fp1); while(fread(&s,sizeof(s),1,fp1)==1) { printf(\nRoll number printf(\nName : printf(\nAge : printf(\nCourse code printf(\nFee : printf(\nDuration of course : } break;

: %d,s.roll_no); %s,s.name); %d,s.age); : %s,s.c_code); %f,s.fee); %s,s.dur);

case 3: ans=Y; while(ans==y || ans==Y) { printf(\nEnter roll number : ); scanf(%d,&n_roll_no); rewind(fp1); while(fread(&s,sizeof(s),1,fp1)==1) { if(n_roll_no==e.roll_no) { printf(\nEnter new name of student : ); scanf(%s,e.name); printf(Age : ); scanf(%d,&s.age); printf(Course code : ); scanf(%s,s.c_code); printf(Fee : ); scanf(%f,&s.fee); printf(Duration of course : ); scanf(%s,s.dur);
72

fseek(fp,-sizeof(e),SEEK_CUR); fwrite(&s,sizeof(s),1,fp1); break; } } } printf(\nModify another record [y/n] : ); fflush(stdin); ans=getche(); } break; case 4 : ans=Y; while(ans==Y || ans==y) { printf(\nEnter roll number of student to delete information :); scanf(%d,&n_roll_no); fp2=fopen(SMTCINEW.DAT,wb); rewind(fp2); while(fread(&s,sizeof(s),1,fp2)==1) { if(n_roll_no==s.roll_no) fwrite(&s,sizeof(s),1,fp2) } fclose(fp1); fclose(fp2); remove(SMTCI.DAT); rename(SMTCINEW.DAT,SMTCI.DAT); fp1=fopen(SMTCI.DAT,rb+); printf(Delete another record (Y/N) : ); fflush(stdin); ans=getche(); } break; case 5 : fclose(fp1); exit(); } } }

73

Exercise 1. Create a text file and copy the contents into another file. 2. Modify the above program to compare the file size. 3. Write a program to create and read a file containing employees personal information, assuming the following data structure: Empno, Name, Address, Basic salary 4. Write a program for generating telephone bill, following information are to be supplied: Serial number, Name of customer, Address, phone number, Amount paid, Date of bill issued, Date of bill paid 5. Write a menu driven program that can perform following operations Insertion of new records Modification of records Deletion of records Listing of records Assume any data structure.

74

You might also like