ansi c programs

120
8/13/2019 Ansi C Programs http://slidepdf.com/reader/full/ansi-c-programs 1/120 Program main( ) { /*…………printing begins………………*/ pr i nt f ( “I see, I r emember ”) ; /*………………pri nti ng ends…………………*/ } Fig 1.2 A program to print one line of text Addi t i on of Two Numbers Program / * ProgrammADDI TI ON l i ne-1 */ /* W r i t t en by EBG l i ne-2 */ mai n() / * l i ne- 3 */ { / * l i ne- 4 */ i nt number; / * l i ne- 5 */ f l oat amount; / * l i ne- 6 */ / * l i ne- 7 */ number = 100; / * l i ne- 8 */ / * l i ne- 9 */ amount = 30. 75 + 75. 35; / * l i ne-10 */ pri nt f ( “%d\ n”, number) ; / * l i ne- 11 */ pri nt f (“%5. 2f ”, amount ) ; / * l i ne- 12 */ } / * l i ne- 13 */ Fig.1.4 Program to add two numbers Program / *-- - - - - - - - - - - - - - - - - - - - I NVESTMENT PROBLEM - - - - - - - - - - - - - - - - - - - - */ #define PERI OD 10 #define PRI NCI PAL 5000. 00 / *-- - - - - - - - - - - - - - - - - - - MAI N PROGRAM BEGI NS - - - - - - - - - - - - - - - - - - - - */ main() { / *-- - - - - - - - - - - - - - - - - - DECLARATI ON STATEMENTS - - - - - - - - - - - - - - - - */ int year ; float amount , val ue, i nr at e; / *-- - - - - - - - - - - - - - - - - - ASSI GNMENT STATEMENTS - - - - - - - - - - - - - - - - - - - */ amount = PRI NCI PAL; i nr at e = 0. 11; year = 0;

Upload: rathnampm

Post on 03-Jun-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 1/120

Program

mai n( ){/ *…………pr i nt i ng begi ns ………………*/

pr i nt f ( “I see, I r emember ”) ;

/ *………………pr i nt i ng ends…………………*/}

Fig 1.2 A program to print one line of text

Addi t i on of Two Number s

Program

/ * Pr ogr amm ADDI TI ON l i ne- 1 *// * Wr i t t en by EBG l i ne- 2 */mai n( ) / * l i ne- 3 * /{ / * l i ne- 4 * /

i nt number ; / * l i ne- 5 */f l oat amount ; / * l i ne- 6 */

/ * l i ne- 7 * /number = 100; / * l i ne- 8 */

/ * l i ne- 9 * /amount = 30. 75 + 75. 35; / * l i ne- 10 */pr i nt f ( “%d\ n”, number ) ; / * l i ne- 11 */pr i nt f ( “%5. 2f ” , amount ) ; / * l i ne- 12 */

} / * l i ne- 13 */

Fig.1.4 Program to add two numbers

Program

/ * - - - - - - - - - - - - - - - - - - - - - I NVESTMENT PROBLEM - - - - - - - - - - - - - - - - - - - - */#define PERI OD 10#define PRI NCI PAL 5000. 00

/ * - - - - - - - - - - - - - - - - - - - - MAI N PROGRAM BEGI NS - - - - - - - - - - - - - - - - - - - - */ main(){ / * - - - - - - - - - - - - - - - - - - - DECLARATI ON STATEMENTS - - - - - - - - - - - - - - - - * /

int year ;float amount , val ue, i nr at e;

/ * - - - - - - - - - - - - - - - - - - - ASSI GNMENT STATEMENTS - - - - - - - - - - - - - - - - - - - * /amount = PRI NCI PAL;i nr at e = 0. 11;year = 0;

Page 2: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 2/120

/ * - - - - - - - - - - - - - - - - - - COMPUTATI ON STATEMENTS - - - - - - - - - - - - - - - - - - - * // *- - - - - - - - - - - - - - - COMPUTATI ON USI NG While LOOP - - - - - - - - - - - - - - - - */

while ( year <= PERI OD){ printf ( “%2d %8. 2f \ n”, year , amount ) ;

val ue = amount + i nr at e * amount ;year = year + 1;amount = val ue;

}/ * - - - - - - - - - - - - - - - - - - - - - - - while LOOP ENDS - - - - - - - - - - - - - - - - - - - - - * / }/ *- - - - - - - - - - - - - - - - - - - - - - - - PROGRAM ENDS - - - - - - - - - - - - - - - - - - - - - - - * /

Fig. 1.5 Program for investment problem

Program

/ * - - - - - - - - - - - - - - - - - - - PROGRAM USI NG FUNCTI ON - - - - - - - - - - - - - - - - - - * /

i nt mul ( i nt a, i nt b) ; / * - - - - - - - DECLARATI ON - - - - - - - - - - - - * /

/ * - - - - - - - - - - - - - - - - - - - - MAI N PROGRAM BEGI NS - - - - - - - - - - - - - - - - - - - - */ main ()

{i nt a, b, c;

a = 5;b = 10;c = mul ( a , b ) ;

printf ( “mul t i pl i cat i on of %d and %d i s %d”, a, b, c) ;}

/ * - - - - - - - - - - - - - - - - MAI N PROGRAM ENDSMUL() FUNCTI ON STARTS - - - - - - - - - - - - - - - - - */

i nt mul ( i nt x, i nt y)i nt p;

p = x*y;{

return ( p) ;}/ * - - - - - - - - - - - - - - - - - - - - MUL ( ) FUNCTI ON ENDS - - - - - - - - - - - - - - - - - - */

Fig.1.7 A Program using a user-defined function

Page 3: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 3/120

Program

/ * - - - - - - - - - - - - - - - PROGRAM USI NG COSI NE FUNCTI ON - - - - - - - - - - - - - - * /#include <math.h>#define PI 3. 1416#define MAX 180

main ( ){

int angl e;float x, y;

angl e = 0; printf ( “ Angl e Cos( angl e) \ n\ n”) ;

while ( angl e <= MAX){

x = ( PI / MAX) *angl e;y = cos( x) ; printf ( “%15d %13. 4f \ n”, angl e, y) ;

angl e = angl e + 10;}

}

Page 4: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 4/120

Example 2.1Representation of integer constants on a 16-bit computer.

The program in Fig.2.9 illustrates the use of integer constants on a 16-bit machine. The output infigure 2.3 shows that the integer values larger than 32767 are not properly stored on a 16-bitmachine. However, when they are qualified as long integer (by appending L), the values are

correctly stored.

I NTEGER NUMBERS ON 16- BI T MACHI NE

Programmai n( ){

pr i nt f ( " I nt eger val ues \ n\ n" ) ;pr i nt f ( " %d %d %d\ n", 32767, 32767+1, 32767+10) ;pr i nt f ( " \ n" ) ;pr i nt f ( "Long i nt eger val ues\ n\ n") ;pr i nt f ( " %l d %l d %l d\ n" , 32767L, 32767L+1L, 32767L+10L) ;

}

OutputI nt eger val ues

32767 - 32768 - 32759

Long i nt eger val ues

32767 32768 32777

Fig. 2.3 Representation of integer constants

Example 2.2 Program in Figure 2.8 shows typical declarations, assignments and values stored in varioustypes of variables.

The variables x and p have been declared as floating-point variables. Note that the way thevalue of 1.234567890000 that we assigned to x is displayed under different output formats. Thevalue of x is displayed as 1.234567880630 under %.12lf format, while the actual value assignedis 1.234567890000. This is because the variable x has been declared as a float that can storevalues only upto six decimal places.

The variable m that has been declared as int is not able to store the value 54321 correctly.Instead, it contains some garbage. Since this program was run on a 16-bit machine, themaximum value that an int variable can store is only 32767. However, the variable k (declaredas unsigned ) has stored the value 54321 correctly. Similarly, the long int variable n has storedthe value 1234567890 correctly.

The value 9.87654321 assigned to y declared as double has been stored correctly but the value

Page 5: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 5/120

is printed as 9.876543 under %lf format. Note that unless specified otherwise, the printf functionwill always display a float or double value to six decimal places. We will discuss later the outputformats for displaying numbers.

EXAMPLES OF ASSI GNMENTS

Program

mai n( ){/ *. . . . . . . . . . DECLARATI ONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . * /

f l oat x, p ;doubl e y, q ;unsi gned k ;

/ * . . . . . . . . . . DECLARATI ONS AND ASSI GNMENTS. . . . . . . . . . . . * /

i nt m = 54321 ;l ong i nt n = 1234567890 ;

/ * . . . . . . . . . . ASSI GNMENTS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . * /

x = 1. 234567890000 ;y = 9. 87654321 ;k = 54321 ;

p = q = 1. 0 ;

/ * . . . . . . . . . . PRI NTI NG. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * /

pr i nt f ( "m = %d\ n", m) ;pr i nt f ( "n = %l d\ n" , n) ;pr i nt f ( "x = %. 12l f \ n" , x) ;pr i nt f ( "x = %f \ n" , x) ;pr i nt f ( "y = %. 12l f \ n" , y) ;pr i nt f ( "y = %l f \ n" , y) ;pr i nt f ( " k = %u p = %f q = %. 12l f \ n" , k, p, q) ;

}

Output

m = - 11215n = 1234567890x = 1. 234567880630x = 1. 234568y = 9. 876543210000

Page 6: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 6/120

y = 9. 876543k = 54321 p = 1. 000000 q = 1. 000000000000

Fig. 2.8 Examples of assignments

Example 2.3

The program in Fig.2.9 illustrates the use of scanf funtion.

The first executable statement in the program is a printf, requesting the user to enter an integernumber. This is known as "prompt message" and appears on the screen like

Enter an integer number

As soon as the user types in an integer number, the computer proceeds to compare the valuewith 100. If the value typed in is less than 100, then a message

Your number is smaller than 100

is printed on the screen. Otherwise, the message

Your number contains more than two digits

is printed. Outputs of the program run for two different inputs are also shown in Fig.2.9.

I NTERACTI VE COMPUTI NG USI NG scanf FUNCTI ONProgram

mai n( ){

i nt number ;

pr i nt f ( "Ent er an i nt eger number \ n" ) ;scanf ( " %d" , &number ) ;

i f ( number < 100 )pr i nt f ( "Your number i s smal l er t han 100\ n\ n" ) ;

el sepr i nt f ( " Your number cont ai ns mor e t han t wo di gi t s\ n" ) ;}

Output

Ent er an i nt eger number54

Page 7: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 7/120

Your number i s smal l er t han 100

Ent er an i nt eger number108

Your number cont ai ns mor e t han t wo di gi t s

Fig.2.9 Use of scanf function

Example 2.4

Sample Program 3 discussed in Chapter 1 can be converted into a more flexible interactiveprogram using scanf as shown in Fig.2.10.

In this case, computer requests the user to input the values of the amount to be invested, interestrate and period of investment by printing a prompt message

Input amount, interest rate, and period

and then waits for input values. As soon as we finish enteringI NTERACTI VE I NVESTMENT PROGRAM

Program

mai n( ){

i nt year , per i od ;f l oat amount , i nr at e, val ue ;

pr i nt f ( "I nput amount , i nt er est r at e, and per i od\ n\ n") ;

scanf ( " %f %f %d" , &amount , &i nr at e, &per i od) ;pr i nt f ( " \ n" ) ;year = 1 ;

whi l e( year <= per i od ){

val ue = amount + i nr at e * amount ;pr i nt f ( "%2d Rs %8. 2f \ n" , year , val ue) ;amount = val ue ;year = year + 1 ;

}}

Output

I nput amount , i nt er est r at e, and per i od

10000 0. 14 5

1 Rs 11400. 00

Page 8: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 8/120

2 Rs 12996. 003 Rs 14815. 444 Rs 16889. 605 Rs 19254. 15

I nput amount , i nt er est r at e, and per i od

20000 0. 12 7

1 Rs 22400. 002 Rs 25088. 003 Rs 28098. 564 Rs 31470. 395 Rs 35246. 846 Rs 39476. 467 Rs 44213. 63

Fig.2.10 Interactive investment program

Page 9: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 9/120

Example 3.1

The program in Fig.3.1 shows the use of integer arithmetic to convert a given number of daysinto months and days.

PROGRAM TO CONVERT DAYS TO MONTHS AND DAYS

Program

mai n ( ){

i nt mont hs, days ;

pr i nt f ( "Ent er days \ n" ) ;scanf ( " %d" , &days) ;

mont hs = days / 30 ;days = days % 30 ;

pr i nt f ( " Mont hs = %d Days = %d", mont hs, days) ;}

Output

Ent er days265

Mont hs = 8 Days = 25Ent er days364Mont hs = 12 Days = 4

Ent er days45Mont hs = 1 Days = 15

_______________________________________________________________

Fig. 3.1 Illustration of integer arithmetic

Example 3.2

Program of Fig.3.2 prints a sequence of squares of numbers. Note the use of the shorthandoperator *= .

The program attempts to print a sequence of squares of numbers starting from 2. The statement

Page 10: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 10/120

a *= a;

which is identical to

a = a*a;

replaces the current value of a by its square. When the value of a becomes equal or greater thanN (=100) the while is terminated. Note that the output contains only three values 2, 4 and 16.

USE OF SHORTHAND OPERATORS

Program

#def i ne N 100#def i ne A 2

mai n( ){

i nt a;

a = A;whi l e( a < N ){

pr i nt f ( "%d\ n" , a) ;a *= a;

}}

Output

2416

Fig. 3.2 Use of shorthand operator *=

Example 3.3

In Fig.3.3, the program employs different kinds of operators. The results of their evaluation arealso shown for comparison.

Notice the way the increment operator ++ works when used in an expression. In the statementc = ++a - b;

new value of a (= 16) is used thus giving the value 6 to c. That is, a is incremented by 1 before itis used in the expression. However, in the statement

d = b++ + a;the old value of b (=10) is used in the expression. Here, b is incremented by 1 after it is used inthe expression.

We can print the character % by placing it immediately after another % character in the controlstring. This is illustrated by the statement

Page 11: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 11/120

printf("a%%b = %d\n", a%b);

The program also illustrates that the expression

c > d ? 1 : 0

assumes the value 0 when c is less than d and 1 when c is greater than d.

I LLUSTRATI ON OF OPERATORS

Program

mai n( ){

i nt a, b, c, d;

a = 15;b = 10;c = ++a - b;

pr i nt f ( " a = %d b = %d c = %d\ n", a, b, c) ;

d = b++ +a;

pr i nt f ( " a = %d b = %d d = %d\ n", a, b, d) ;

pr i nt f ( "a/ b = %d\ n", a/ b) ;pr i nt f ( " a%%b = %d\ n" , a%b) ;pr i nt f ( " a *= b = %d\ n" , a*=b) ;

pr i nt f ( "%d\ n", ( c>d) ? 1 : 0) ;pr i nt f ( "%d\ n", ( c<d) ? 1 : 0) ;}

Output

a = 16 b = 10 c = 6a = 16 b = 11 d = 26a/ b = 1a%b = 5a * = b = 176

01

Fig. 3.3 Further illustration of arithmetic operators

Page 12: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 12/120

Example 3.4

The program in Fig.3.4 illustrates the use of variables in expressions and their evaluation.

Output of the program also illustrates the effect of presence of parentheses in expressions. Thisis discussed in the next section.

EVALUATI ON OF EXPRESSI ONS

Program

mai n( ){

f l oat a, b, c , x, y, z ;

a = 9;b = 12;c = 3;

x = a - b / 3 + c * 2 - 1;y = a - b / ( 3 + c) * ( 2 - 1) ;z = a - ( b / ( 3 + c) * 2) - 1;

pr i nt f ( "x = %f \ n" , x) ;pr i nt f ( "y = %f \ n" , y) ;pr i nt f ( "z = %f \ n" , z ) ;

}

Output

x = 10. 000000y = 7. 000000z = 4. 000000

Fig.3.4 Illustrations of evaluation of expressions

Example 3.5

Output of the program in Fig.3.6 shows round-off errors that can occur in computation offloating point numbers.

PROGRAM SHOWI NG ROUND- OFF ERRORS

Program

/ *- - - - - - - - - - - - - - - - - - - Sum of n t er ms of 1/ n - - - - - - - - - - - - - - - - - - - * /mai n( ){

Page 13: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 13/120

f l oat sum, n, t erm ;i nt count = 1 ;

sum = 0 ;pr i nt f ( "Ent er val ue of n\ n" ) ;

scanf ( "%f " , &n) ;

t er m = 1. 0/ n ;whi l e( count <= n ){

sum = sum + t er m ;count ++ ;

}pr i nt f ( "Sum = %f \ n", sum) ;

}

Output

Ent er val ue of n99Sum = 1. 000001Ent er val ue of n143Sum = 0. 999999

Fig.3.6 Round-off errors in floating point computations

We know that the sum of n terms of 1/n is 1. However, due to errors in floating pointrepresentation, the result is not always 1.

Example 3.6

Figure 3.8 shows a program using a cast to evaluate the equationn

sum = ∑ (1/i)i=1

PROGRAM SHOWI NG THE USE OF A CAST

Program

mai n( ){

f l oat s um ;i nt n ;

sum = 0 ;

f or ( n = 1 ; n <= 10 ; ++n ){

sum = sum + 1/ ( f l oat ) n ;

Page 14: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 14/120

pr i nt f ( " %2d %6. 4f \ n", n, sum) ;}

}

Output

1 1. 00002 1. 50003 1. 83334 2. 08335 2. 28336 2. 45007 2. 59298 2. 71799 2. 8290

10 2. 9290

Fig. 3.8 Use of a cast

Page 15: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 15/120

Example 4.1

The program in Fig.4.1 shows the use of getchar function in an interactive environment.

The program displays a question of YES/NO type to the user and reads the user'sresponse in a single character (Y or N). If the response is Y, it outputs the message

My name is BUSY BEE

otherwise, outputs.

You are good for nothing

Note there is one line space between the input text and output message.

READING A CHARACTER FROM KEYBOARD

Program

#i ncl ude <st di o. h>

mai n( ){

char answer ;

pr i nt f ( " Woul d you l i ke t o know my name?\ n" ) ;pr i nt f ( " Type Y f or YES and N f or NO: " ) ;

answer = get char ( ) ; / * . . . . Readi ng a char acter. . . */

i f ( answer == ' Y' | | answer == ' y' )pr i nt f ( " \ n\ nMy name i s BUSY BEE\ n" ) ;

el sepr i nt f ( " \ n\ nYou ar e good f or not hi ng\ n") ;

}

Output

Woul d you l i ke t o know my name? Type Y f or YES and N f or NO: Y

My name i s BUSY BEE

Woul d you l i ke t o know my name? Type Y f or YES and N f or NO: n

Page 16: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 16/120

You ar e good f or not hi ng

Fig.4.1 Use of getchar function

Example 4.2The program of Fig.4.2 requests the user to enter a character and displays a message on thescreen telling the user whether the character is an alphabet or digit, or any other specialcharacter.

This program receives a character from the keyboard and tests whether it is a letter ordigit and prints out a message accordingly. These tests are done with the help of thefollowing functions:

isalpha(character)

isdigit(character)For example, isalpha assumes a value non-zero (TRUE) if the argument character contains analphabet; otherwise it assumes 0 (FALSE). Similar is the case with the function isdigit .

TESTI NG CHARACTER TYPE

Program:

#i ncl ude <st di o. h>#i ncl ude <ct ype. h>

mai n( ){

char char act er ;

pr i nt f ( "Press any key\ n") ;char act er = get char ( ) ;

i f ( i sal pha( char acter) > 0)pr i nt f ( "The char act er i s a l et t er . " ) ;

el sei f ( i sdi gi t ( char act er ) > 0)

pr i nt f ( "The char act er i s a di gi t . " ) ;

el sepr i nt f ( "The char act er i s not al phanumer i c. ") ;

}

Output

Pr ess any keyh

The char act er i s a l et t er .

Pr ess any key5

Page 17: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 17/120

The char acter i s a di gi t .

Pr ess any key*

The char act er i s not al phanumer i c. ________________________________________________________________________

Fig.4.2 Program to test the characte r type

Example 4.3

A program that reads a character from keyboard and then prints it in reverse case is given inFig.4.3. That is, if the input is upper case, the output will be lower case and vice versa.

The program uses three new functions: islower, toupper , and tolower . The function islower isa conditional function and takes the value TRUE if the argument is a lower case alphabet;otherwise takes the value FALSE. The function toupper converts the lower case argument intoan upper case alphabet while the function tolower does the reverse.

WRI TI NG A CHARACTER TO THE SCREEN

Program

#i ncl ude <st di o. h>#i ncl ude <ct ype. h>

mai n( ){

char al phabet ;

pr i nt f ( "Ent er an al phabet ") ;put char ( ' \ n' ) ; / * move t o next l i ne */al phabet = get char ( ) ;

i f ( i s l ower ( al phabet ) )put char ( t oupper ( al phabet ) ) ;

el seput char ( t ol ower ( al phabet ) ) ;

}

Page 18: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 18/120

OutputEnt er an al phabetaAEnt er an al phabetQqEnt er an al phabetzZ

Fig.4.3 Reading and writing of alphabets in reverse case

Example 4.4

Various input formatting options for reading integers are experimented in the program shown

in Fig. 4.4.

The first scanf requests input data for three integer values a, b, and c, and accordingly threevalues 1, 2, and 3 are keyed in. Because of the specification %*d the value 2 has been skippedand 3 is assigned to the variable b . Notice that since no data is available for c, it containsgarbage.

The second scanf specifies the format %2d and %4d for the variables x and y respectively.Whenever we specify field width for reading integer numbers, the input numbers should notcontain more digits that the specified size. Otherwise, the extra digits on the right-hand side willbe truncated and assigned to the next variable in the list. Thus, the second scanf has truncatedthe four digit number 6789 and assigned 67 to x and 89 to y. The value 4321 has been assignedto the first variable in the immediately following scanf statement.

Page 19: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 19/120

READI NG INTEGER NUMBERS

Program:

mai n( ){

i nt a, b, c, x, y, z ;i nt p, q, r ;

pr i nt f ( "Ent er t hr ee i nt eger number s\ n") ;scanf ( " %d %*d %d", &a, &b, &c) ;pr i nt f ( "%d %d %d \ n\ n", a, b, c) ;

pr i nt f ( "Ent er t wo 4- di gi t number s\ n") ;scanf ( " %2d %4d", &x, &y) ;pr i nt f ( "%d %d\ n\ n", x, y) ;

pr i nt f ( "Ent er t wo i nt eger s \ n") ;scanf ( " %d %d", &a, &x) ;

pr i nt f ( "%d %d \ n\ n", a, x) ;pr i nt f ( "Ent er a ni ne di gi t number \ n") ;scanf ( " %3d %4d %3d" , &p, &q, &r ) ;pr i nt f ( "%d %d %d \ n\ n", p, q, r ) ;

pr i nt f ( "Ent er t wo t hr ee di gi t number s\ n") ;scanf ( " %d %d", &x, &y) ;pr i nt f ( "%d %d", x, y) ;

}

Output

Ent er t hr ee i nt eger number s1 2 31 3 - 3577

Ent er t wo 4- di gi t number s6789 432167 89

Ent er t wo i nt eger s44 664321 44

Ent er a ni ne- di gi t number

12345678966 1234 567

Ent er t wo t hr ee- di gi t number s123 45689 123

Fig.4.4 Reading integers using scanf

Page 20: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 20/120

Example 4.5Reading of real numbers (in both decimal point and exponential notation) is illustrated inFig.4.5.

READI NG OF REAL NUMBERS

Program : mai n( ){

f l oat x, y;doubl e p, q;

pr i nt f ( "Val ues of x and y: ") ;scanf ( " %f %e", &x, &y) ;pr i nt f ( " \ n" ) ;pr i nt f ( "x = %f \ ny = %f \ n\ n", x, y) ;

pr i nt f ( "Val ues of p and q: ") ;scanf ( "%l f %l f ", &p, &q) ;pr i nt f ( "\ np = %l f \ nq = %e" , p, q) ;pr i nt f ( "\ n\ np = %. 12l f \ np = %. 12e" , p, q) ;

}

Output

Val ues of x and y: 12. 3456 17. 5e- 2

x = 12. 345600y = 0. 175000

Val ues of p and q: 4. 142857142857 18. 5678901234567890p = 4. 142857142857 q = 1. 856789012346e+001

Fig.4.5 Reading of real numbers

Example 4.6

Reading of strings using %wc and %ws is illustrated in Fig.4.6.

The program in Fig.4.6 illustrates the use of various field specifications for reading strings. Whenwe use %wc for reading a string, the system will wait until the wth character is keyed in.

Note that the specification %s terminates reading at the encounter of a blank space.Therefore, name2 has read only the first part of "New York" and the second part isautomatically assigned to name3 . However, during the second run, the string "New-

Page 21: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 21/120

York" is correctly assigned to name2 .

READI NG STRI NGS

Program

mai n( ){

i nt no;char name1[ 15] , name2[ 15] , name3[ 15] ;

pr i nt f ( " Ent er ser i al number and name one\ n" ) ;scanf ( " %d %15c" , &no, name1) ;

pr i nt f ( " %d %15s\ n\ n" , no, name1) ;pr i nt f ( " Ent er ser i al number and name t wo\ n" ) ;scanf ( " %d %s" , &no, name2) ;pr i nt f ( " %d %15s\ n\ n" , no, name2) ;

pr i nt f ( "Ent er ser i al number and name t hr ee\ n" ) ;scanf ( " %d %15s" , &no, name3) ;pr i nt f ( " %d %15s\ n\ n" , no, name3) ;

}

Output

Ent er ser i al number and name one1 1234567890123451 123456789012345r

Ent er ser i al number and name t wo2 New Yor k2 New

Ent er ser i al number and name t hr ee2 Yor k

Ent er ser i al number and name one1 1234567890121 123456789012 r

Ent er ser i al number and name t wo2 New- Yor k2 New- Yor kEnt er ser i al number and name t hr ee3 London3 London

Page 22: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 22/120

Fig. 4.6 Reading of strings

Example 4.7The program in Fig. 4.7 illustrates the function of %[ ] specification.

I LLUSTRATI ON OF %[ ] SPECI FI CATI ON

Program-A

mai n( ){

char addr ess[ 80] ;

pr i nt f ( "Ent er addr ess \ n") ;scanf ( "%[ a- z’ ] " , addr ess) ;pr i nt f ( "%- 80s\ n\ n", addr ess) ;

}

Output

Ent er addr essnew del hi 110002new del hi

I LLUSTRATI ON OF %[ ^ ] SPECI FI CATI ON

Program-B

mai n( ){

char addr ess[ 80] ;

pr i nt f ( "Ent er addr ess \ n") ;scanf ( " %[ \ n] " , addr ess) ;pr i nt f ( "%- 80s", addr ess) ;

}

Output

Ent er addr essNew Del hi 110 002New Del hi 110 002

Fig.4.7 Illustration of conversion specification%[] for strings

Page 23: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 23/120

Example 4.8The program presented in Fig.4.8 illustrates the testing for correctness of reading of data byscanf function.

The function scanf is expected to read three items of data and therefore, when the values for allthe three variables are read correctly, the program prints out their values. During the third run,the second item does not match with the type of variable and therefore the reading is terminatedand the error message is printed. Same is the case with the fourth run.

In the last run, although data items do not match the variables, no error message has been printed. When we attempt to read a real number for an int variable, the integer part isassigned to the variable, and the truncated decimal part is assigned to the next variable.Note that the character `2' is assigned to the character variable c.

TESTI NG FOR CORRECTNESS OF I NPUT DATA

Program

mai n( )

{ i nt a;f l oat b;char c;

pr i nt f ( "Ent er val ues of a, b and c\ n") ;

i f ( scanf ( " %d %f %c" , &a, &b, &c) == 3)pr i nt f ( " a = %d b = %f c = %c\ n" , a, b, c) ;

el sepr i nt f ( " Er r or i n i nput . \ n" ) ;

}

Output Ent er val ues of a, b and c12 3. 45 Aa = 12 b = 3. 450000 c = A

Ent er val ues of a, b and c23 78 9a = 23 b = 78. 000000 c = 9

Ent er val ues of a, b and c8 A 5. 25

Er ror i n i nput .Ent er val ues of a, b and c

Y 12 67

Er ror i n i nput .Ent er val ues of a, b and c15. 75 23 X

a = 15 b = 0. 750000 c = 2

Fig.4.8 Detection of errors in scanf input

Page 24: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 24/120

Example 4.9

The program in Fig.4.9 illustrates the output of integer numbers under various formats.

PRI NTI NG OF INTEGER NUMBERS

Program: mai n( ){

i nt m = 12345;l ong n = 987654;

pr i nt f ( "%d\ n", m) ;pr i nt f ( "%10d\ n", m) ;pr i nt f ( "%010d\ n", m) ;pr i nt f ( "%- 10d\ n", m) ;pr i nt f ( "%10l d\ n" , n) ;

pr i nt f ( "%10l d\ n" , - n) ;}

Output

1234512345

000001234512345

987654- 987654

Fig.4.9 Formatted output of integers

Example 4.10 All the options of printing a real number are illustrated in Fig.4.10.

PRI NTI NG OF REAL NUMBERS

Program :

mai n( )

{ f l oat y = 98. 7654;

pr i nt f ( "%7. 4f \ n" , y) ;pr i nt f ( " %f \ n" , y) ;pr i nt f ( "%7. 2f \ n" , y) ;pr i nt f ( " %- 7. 2f \ n" , y) ;pr i nt f ( "%07. 2f \ n" , y) ;pr i nt f ( " %* . * f " , 7, 2, y) ;

Page 25: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 25/120

pr i nt f ( " \ n" ) ;pr i nt f ( "%10. 2e\ n" , y) ;pr i nt f ( "%12. 4e\ n" , - y) ;pr i nt f ( "%- 10. 2e\ n" , y) ;pr i nt f ( "%e\ n" , y) ;

}

Output 98. 765498. 76540498. 7798. 770098. 7798. 779. 88e+001- 9. 8765e+0019. 88e+0019. 876540e+001

Fig.4.10 Formatted output of real numbers

Example 4.11

Printing of characters and strings is illustrated in Fig.4.11.

PRI NTI NG OF CHARACTERS AND STRI NGS

Program

mai n( ){

char x = ' A' ;st at i c char name[ 20] = " ANI L KUMAR GUPTA" ;

pr i nt f ( " OUTPUT OF CHARACTERS\ n\ n") ;pr i nt f ( " %c\ n%3c\ n%5c\ n" , x, x, x) ;pr i nt f ( "%3c\ n%c\ n", x, x) ;pr i nt f ( " \ n" ) ;

pr i nt f ( " OUTPUT OF STRI NGS\ n\ n" ) ;pr i nt f ( "%s\ n", name) ;pr i nt f ( " %20s\ n" , name) ;pr i nt f ( " %20. 10s\ n", name) ;pr i nt f ( "%. 5s\ n", name) ;pr i nt f ( "%- 20. 10s\ n", name) ;pr i nt f ( " %5s\ n" , name) ;

}

Page 26: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 26/120

Output

OUTPUT OF CHARACTERS

AA

AA

A

OUTPUT OF STRI NGS

ANI L KUMAR GUPTAANI L KUMAR GUPTA

ANI L KUMARANI LANI L KUMARANI L KUMAR GUPTA

Fig.4.11 Printing of characters and strings

Page 27: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 27/120

Example 5.1The program in Fig.5.3 reads four values a, b, c, and d from the terminal and evaluates theratio of (a+b) to (c-d) and prints the result, if c-d is not equal to zero.

The program given in Fig.5.3 has been run for two sets of data to see that the pathsfunction properly. The result of the first run is printed as

Ratio = -3.181818

I LLUSTRATI ON OF if STATEMENT

Program

mai n( ){

i nt a, b, c, d;f l oat r at i o;

pr i nt f ( "Ent er f our i nt eger val ues\ n") ;scanf ( " %d %d %d %d", &a, &b, &c, &d) ;

i f ( c- d ! = 0) / * Execut e st at ement bl ock */{

r at i o = ( f l oat ) ( a+b) / ( f l oat ) ( c- d) ;pr i nt f ( "Rat i o = %f \ n" , r at i o) ;

}}

Output

Ent er f our i nt eger val ues12 23 34 45Rat i o = - 3. 181818

Ent er f our i nt eger val ues12 23 34 34

Fig. 5.3 Illustration of simple if statement

Example 5.2

The program in Fig.5.4 counts the number of boys whose weight is less than 50 kgs and heightis greater than 170 cm.

The program has to test two conditions, one for weight and another for height. This isdone using the compound relation

Page 28: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 28/120

if (weigh t < 50 && height > 170)

This would have been equivalently done using two if statements as follows:

if (weight < 50)if (height > 170)

count = count +1;

If the value of weight is less than 50, then the following statement is executed, which in turn isanother if statement. This if statement tests height and if the height is greater than 170, thenthe count is incremented by 1.

Page 29: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 29/120

COUNTI NG WI TH if

Program

mai n( ){

i nt count , i ;f l oat wei ght , hei ght ;

count = 0;pr i nt f ( "Ent er wei ght and hei ght f or 10 boys\ n" ) ;

f or ( i =1; i <= 10; i ++){

scanf ( " %f %f " , &wei ght , &hei ght ) ;i f ( wei ght < 50 && hei ght > 170)

count = count + 1;

}

pr i nt f ( " Number of boys wi t h wei ght < 50 kgs\ n" ) ;pr i nt f ( " and hei ght > 170 cm = %d\ n" , count ) ;

}

Output

Ent er wei ght and hei ght f or 10 boys45 176. 5

55 174. 2

47 168. 0

49 170. 7

54 169. 0

53 170. 5

49 167. 0

48 175. 0

47 167

51 170

Number of boys wi t h wei ght < 50 kgsand hei ght > 170 cm = 3

Fig. 5.4 Use of if for counting

Page 30: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 30/120

Example 5.3

A program to evaluate the power series

x2

x3

xn

e x = 1 + x + --- + --- + ..... + ---- , 0 < x < 12! 3! n!

is given in Fig. 5.6. It uses if......else to test the accuracy.

Page 31: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 31/120

xn

The power series contains the recurrence relationship of the type

Tn = T n-1 (---) for n > 1

T 1 = x for n = 1

T 0 = 1

If Tn-1 (usually known as previous term ) is known, then T n (known as present term ) can be easilyfound by multiplying the previous term by x/n. Then

e x = T 0 + T 1 + T 2 + ...... + T n = sum

EXPERI MENT WI TH if...else STATEMENT

Program

#def i ne ACCURACY 0. 0001

mai n( ){

i nt n, count ;f l oat x, t er m, sum;

pr i nt f ( "Ent er val ue of x: " ) ;scanf ( "%f ", &x) ;

n = t er m = sum = count = 1;

whi l e ( n <= 100){

t er m = t erm * x/ n;sum = sum + t er m;count = count + 1;i f ( t er m < ACCURACY)

n = 999;el se

n = n + 1;}

pr i nt f ( " Ter ms = %d Sum = %f \ n" , count , sum) ;

}

Output

Ent er val ue of x: 0

Page 32: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 32/120

Ter ms = 2 Sum = 1. 000000

Ent er val ue of x: 0. 1 Ter ms = 5 Sum = 1. 105171

Ent er val ue of x: 0. 5

Ter ms = 7 Sum = 1. 648720

Ent er val ue of x: 0. 75 Ter ms = 8 Sum = 2. 116997

Ent er val ue of x: 0. 99 Ter ms = 9 Sum = 2. 691232

Ent er val ue of x: 1 Ter ms = 9 Sum = 2. 718279

Fig 5.6 Illustration of if...else statement

Example 5.4The program in Fig. 5.8 selects and prints the largest of the three numbers using nestedif....else statements.

SELECTI NG THE LARGEST OF THREE VALUES

Program

mai n( ){

f l oat A, B, C;

pr i nt f ( "Ent er t hr ee val ues\ n") ;scanf ( " %f %f %f " , &A, &B, &C) ;

pr i nt f ( " \ nLarges t val ue i s " ) ;

i f ( A>B){

i f ( A>C)pr i nt f ( " %f \ n" , A) ;

el sepr i nt f ( " %f \ n" , C) ;

}el se{

i f ( C>B)pr i nt f ( " %f \ n" , C) ;

Page 33: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 33/120

el sepr i nt f ( " %f \ n" , B) ;

} }

Output

Ent er t hr ee val ues23445 67379 88843

Lar gest val ue i s 88843. 000000

Fig 5.8 Selecting the largest of three numbers

Example 5.5

An electric power distribution company charges its domestic consumers as follows:Consumption Units Rate of Charge

0 - 200 Rs. 0.50 per unit201 - 400 Rs. 100 plus Rs.0.65 per unit excess of 200401 - 600 Rs. 230 plus Rs.0.80 per unit excess of 400601 and above Rs. 390 plus Rs.1.00 per unit excess of 600

The program in Fig.5.10 reads the customer number and power consumed and printsthe amount to be paid by the customer.

USE OF else if LADDER

Program

mai n( ){

i nt uni t s, cust num;f l oat char ges;

pr i nt f ( " Ent er CUSTOMER NO. and UNI TS consumed\ n") ;scanf ( " %d %d" , &cust num, &uni t s) ;

i f ( uni t s <= 200)char ges = 0. 5 * uni t s;

el se i f ( uni t s <= 400)

char ges = 100 + 0. 65 * ( uni t s - 200) ;el se i f ( uni t s <= 600)char ges = 230 + 0. 8 * ( uni t s - 400) ;

el sechar ges = 390 + ( uni t s - 600) ;

pr i nt f ( " \ n\ nCust omer No: %d: Char ges = %. 2f \ n" ,cust num, char ges) ;

}

Page 34: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 34/120

Output

Ent er CUSTOMER NO. and UNI TS consumed 101 150Cust omer No: 101 Char ges = 75. 00

Ent er CUSTOMER NO. and UNI TS consumed 202 225

Cust omer No: 202 Char ges = 116. 25

Ent er CUSTOMER NO. and UNI TS consumed 303 375Cust omer No: 303 Char ges = 213. 75

Ent er CUSTOMER NO. and UNI TS consumed 404 520Cust omer No: 404 Char ges = 326. 00

Ent er CUSTOMER NO. and UNI TS consumed 505 625Cust omer No: 505 Char ges = 415. 00

Fig. 5.10 Illustration of else..if ladder

Example 5.6

An employee can apply for a loan at the beginning of every six months, but he will besanctioned the amount according to the following company rules:

Rule 1 : An employee cannot enjoy more than two loans at any point of time.Rule 2 : Maximum permissible total loan is limited and depends upon the category of the

employee.

A program to process loan applications and to sanction loans is given in Fig. 5.12.CONDITIONAL OPERATOR

Program

#def i ne MAXLOAN 50000

mai n( ){

l ong i nt l oan1, l oan2, l oan3, sancl oan, sum23;

pr i nt f ( "Ent er t he val ues of pr evi ous t wo l oans: \ n") ;scanf ( " %l d %l d" , &l oan1, &l oan2) ;

pr i nt f ( "\ nEnt er t he val ue of new l oan: \ n") ;scanf ( " %l d" , &l oan3) ;

sum23 = l oan2 + l oan3;sancl oan = ( l oan1>0) ? 0 : ( ( sum23>MAXLOAN) ?

MAXLOAN - l oan2 : l oan3) ;

Page 35: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 35/120

pr i nt f ( " \ n\ n" ) ;pr i nt f ( "Pr evi ous l oans pendi ng: \ n%l d %l d\ n" , l oan1, l oan2) ;pr i nt f ( "Loan r equest ed = %l d\ n" , l oan3) ;pr i nt f ( "Loan sanct i oned = %l d\ n" , sancl oan) ;

}

Output

Ent er t he val ues of pr evi ous t wo l oans:0 20000

Ent er t he val ue of new l oan:45000

Pr evi ous l oans pendi ng:0 20000Loan r equest ed = 45000

Loan sanct i oned = 30000Ent er t he val ues of pr evi ous t wo l oans:1000 15000

Ent er t he val ue of new l oan:25000

Pr evi ous l oans pendi ng:1000 15000Loan r equest ed = 25000Loan sanct i oned = 0

Fig 5.12 Illustration of the conditional operator

Example 5.7

Program presented in Fig.5.13 illustrates the use of the goto statement.

The program evaluates the square root for five numbers. The variable count keeps the countof numbers read. When count is less than or equal to 5, goto read ; directs the control to thelabel read ; otherwise, the program prints a message and stops.

USE OF goto STATEMENT

Program

#i ncl ude <mat h. h>mai n( ){

doubl e x, y;

Page 36: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 36/120

i nt count ;

count = 1;

pr i nt f ( "Ent er FI VE r eal val ues i n a LI NE \ n") ;

r ead:scanf ( "%l f " , &x) ;pr i nt f ( " \ n" ) ;i f ( x < 0)

pr i nt f ( "Val ue - %d i s negat i ve\ n", count ) ;el se{

y = sqr t ( x) ;pr i nt f ( " %l f \ t %l f \ n" , x, y) ;

}

count = count + 1;

i f ( count <= 5)got o r ead;

pr i nt f ( "\ nEnd of comput at i on") ;}

Output

Ent er FI VE r eal val ues i n a LI NE50. 70 40 - 36 75 11. 2550. 750000 7. 12390340. 000000 6. 324555

Val ue - 3 i s negat i ve75. 000000 8. 66025411. 250000 3. 354102End of comput at i on

Fig.5.13 Use of the goto statement

Page 37: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 37/120

Example 6.1

A program to evaluate the equationy = x n

when n is a non-negative integer, is given in Fig.6.2

The variable y is initialized to 1 and then multiplied by x, n times using the while loop. The loopcontrol variable, count is initialized outside the loop and incremented inside the loop. When thevalue of count becomes greater than n , the control exists the loop.

EXAMPLE OF while STATEMENT

Program

mai n( ){

i nt count , n;f l oat x, y;

pr i nt f ( "Ent er t he val ues of x and n : ") ;scanf ( " %f %d" , &x, &n) ;y = 1. 0;count = 1; / * I ni t i al i s at i on * /

/ * LOOP BEGI Ns */

whi l e ( count <= n) / * Test i ng */{

y = y*x;count ++; / * I ncr ement i ng */

}/ * END OF LOOP */pr i nt f ( " \ nx = %f ; n = %d; x t o power n = %f \ n" , x, n, y) ;

}

Output

Ent er t he val ues of x and n : 2. 5 4x = 2. 500000; n = 4; x t o power n = 39. 062500

Ent er t he val ues of x and n : 0. 5 4

x = 0. 500000; n = 4; x t o power n = 0. 062500

Fig.6. 2 Program to compute x to the power n using while loop

Page 38: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 38/120

Example 6.2

A program to print the multiplication table from 1 x 1 to 12 x 10 as shown below is given in Fig.6.3.

1 2 3 4 ......... 10

2 4 6 8 ......... 20

3 6 9 12 ......... 30

4 ......... 40

- -

- -

- -

12 . . . ........ 120

This program contains two do.... while loops in nested form. The outer loop is controlled by the

variable row and executed 12 times. The inner loop is controlled by the variable column and isexecuted 10 times, each time the outer loop is executed. That is, the inner loop is executed atotal of 120 times, each time printing a value in the table.

PRINTING OF MULTIPLICATION TABLE

Program:

#def i ne COLMAX 10#def i ne ROWMAX 12

mai n( ){

i nt r ow, col umn, y;

r ow = 1;pr i nt f ( " MULTI PLI CATI ON TABLE \ n" ) ;pr i nt f ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n" ) ;do / * . . . . . . OUTER LOOP BEGI NS. . . . . . . . * /{

col umn = 1;

do / * . . . . . . . I NNER LOOP BEGI NS. . . . . . . * /{

y = r ow * col umn;pr i nt f ( "%4d" , y) ;col umn = col umn + 1;

}while ( col umn <= COLMAX) ; / * . . . I NNER LOOP ENDS . . . */

pr i nt f ( " \ n" ) ;r ow = r ow + 1;

}while ( r ow <= ROWMAX) ; / *. . . . . OUTER LOOP ENDS . . . . . */

Page 39: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 39/120

pr i nt f ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n" ) ;}

OutputMULTI PLI CATI ON TABLE

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -1 2 3 4 5 6 7 8 9 102 4 6 8 10 12 14 16 18 203 6 9 12 15 18 21 24 27 304 8 12 16 20 24 28 32 36 405 10 15 20 25 30 35 40 45 506 12 18 24 30 36 42 48 54 607 14 21 28 35 42 49 56 63 708 16 24 32 40 48 56 64 72 809 18 27 36 45 54 63 72 81 9010 20 30 40 50 60 70 80 90 10011 22 33 44 55 66 77 88 99 11012 24 36 48 60 72 84 96 108 120

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Fig.6.3 Printing of a multiplication table using do...while loop

Example 6.3

The program in Fig.6.4 uses a for loop to print the "Powers of 2" table for the power 0 to 20,both positive and negative.

The program evaluates the valuep = 2 n

successively by multiplying 2 by itself n times.1

q = 2 -n = ----p

Note that we have declared p as a long int and q as a double .

Addi tional Featu res of fo r Loop

The for loop in C has several capabilities that are not found in other loop constructs. Forexample, more than one variable can be initialized at a time in the for statement. The statements

p = 1;

for (n=0; n<17; ++n)

can be rewritten as

for (p=1, n=0; n<17; ++n )

Page 40: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 40/120

USE OF for LOOP

Program:

mai n( ){

l ong i nt p;i nt n;doubl e q;pr i nt f ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n" ) ;pr i nt f ( " 2 t o power n n 2 t o power - n\ n") ;pr i nt f ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n" ) ;p = 1;for ( n = 0; n < 21 ; ++n) / * LOOP BEGI NS */{

i f ( n == 0)p = 1;

el sep = p * 2;

q = 1. 0/ ( doubl e) p ;pr i nt f ( " %10l d %10d %20. 12l f \ n" , p, n, q) ;} / * LOOP ENDS */pr i nt f ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n" ) ;

}

Output --------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -2 t o power n n 2 t o power - n

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -1 0 1. 0000000000002 1 0. 5000000000004 2 0. 2500000000008 3 0. 125000000000

16 4 0. 06250000000032 5 0. 03125000000064 6 0. 015625000000

128 7 0. 007812500000256 8 0. 003906250000512 9 0. 001953125000

1024 10 0. 0009765625002048 11 0. 0004882812504096 12 0. 0002441406258192 13 0. 000122070313

16384 14 0. 000061035156

32768 15 0. 00003051757865536 16 0. 000015258789131072 17 0. 000007629395262144 18 0. 000003814697524288 19 0. 000001907349

1048576 20 0. 000000953674- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Fig.6.4 Program to print 'Power of 2' table using for loop

Page 41: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 41/120

Example 6.4

A class of n students take an annual examination in m subjects. A program to read themarks obtained by each student in various subjects and to compute and print the total marksobtained by each of them is given in Fig.6.5.

The program uses two for loops, one for controlling the number of students and the other forcontrolling the number of subjects. Since both the number of students and the number ofsubjects are requested by the program, the program may be used for a class of any size and anynumber of subjects.

The outer loop includes three parts:

(1) reading of roll-numbers of students, one after another,

(2) inner loop, where the marks are read and totaled for each student, and

(3) printing of total marks and declaration of grades.

Page 42: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 42/120

I LLUSTRATI ON OF NESTED LOOPS

Program

#def i ne FI RST 360

#def i ne SECOND 240

mai n( )

{

i nt n, m, i , j ,

r ol l _number , mar ks, t ot al ;

pr i nt f ( "Ent er number of st udent s and subj ect s\ n" ) ;

scanf ( " %d %d", &n, &m) ;

pr i nt f ( " \ n" ) ;

f or ( i = 1; i <= n ; ++i )

{

pr i nt f ( "Ent er r ol l _number : " ) ;

scanf ( " %d" , &r ol l _number ) ;

t ot al = 0 ;

pr i nt f ( " \ nEnt er marks of %d subj ect s f or ROLL NO %d\ n" ,

m, r ol l _number ) ;f or ( j = 1; j <= m; j ++)

{

scanf ( " %d" , &marks) ;

t ot al = t ot al + mar ks;

}

pr i nt f ( " TOTAL MARKS = %d " , t ot al ) ;

i f ( t ot al >= FI RST)

pr i nt f ( " ( Fi r s t Di vi si on ) \ n\ n" ) ;

el se i f ( t ot al >= SECOND)

pr i nt f ( " ( Second Di vi s i on ) \ n\ n") ;

el se

pr i nt f ( " ( * ** F A I L * ** ) \ n\ n" ) ;

}

}

Page 43: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 43/120

Output Ent er number of st udent s and subj ect s3 6

Ent er r ol l _number : 8701Ent er mar ks of 6 subj ect s f or ROLL NO 870181 75 83 45 61 59

TOTAL MARKS = 404 ( Fi r st Di vi si on )

Ent er r ol l _number : 8702

Ent er mar ks of 6 subj ect s f or ROLL NO 870251 49 55 47 65 41

TOTAL MARKS = 308 ( Second Di vi si on )

Ent er r ol l _number : 8704Ent er mar ks of 6 subj ect s f or ROLL NO 870440 19 31 47 39 25

TOTAL MARKS = 201 ( *** F A I L *** )

Fig.6.5 Illustration of nested for loops

Example 6.5

The program in Fig.6.8 illustrates the use of the break statement in a C program.

The program reads a list of positive values and calculates their average. The for loop is writtento read 1000 values. However, if we want the program to calculate the average of any set ofvalues less than 1000, then we must enter a 'negative' number after the last value in the list, tomark the end of input.

USE OF break I N A PROGRAM

Program

mai n( ){

i nt m;f l oat x, sum, aver age;

pr i nt f ( " Thi s pr ogr am comput es t he aver age of aset of number s\ n" ) ;

pr i nt f ( "Ent er val ues one af t er anot her \ n") ;pr i nt f ( " Ent er a NEGATI VE number at t he end. \ n\ n" ) ;sum = 0;f or ( m = 1 ; m < = 1000 ; ++m){

scanf ( "%f ", &x) ;i f ( x < 0)

break;sum += x ;

}

Page 44: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 44/120

aver age = sum/ ( f l oat ) ( m- 1) ;pr i nt f ( " \ n" ) ;pr i nt f ( " Number of val ues = %d\ n" , m- 1) ;pr i nt f ( "Sum = %f \ n", sum) ;pr i nt f ( "Aver age = %f \ n" , aver age) ;

}

Output

Thi s pr ogr am comput es t he aver age of a set of number sEnt er val ues one af t er anot herEnt er a NEGATI VE number at t he end.

21 23 24 22 26 22 - 1

Number of val ues = 6Sum = 138. 000000Aver age = 23. 000000

Fig.6.8 Use of break in a program

Example 6.6

A program to evaluate the series1

------ = 1 + x + x 2 + x 3 + ..... + x n 1-x

for -1 < x < 1 with 0.01 per cent accuracy is given in Fig.6.9. The goto statement is used toexit the loop on achieving the desired accuracy.

We have used the for statement to perform the repeated addition of each of the terms in theseries. Since it is an infinite series, the evaluation of the function is terminated when the term x n reaches the desired accuracy. The value of n that decides the number of loop operations is notknown and therefore we have decided arbitrarily a value of 100, which may or may not result inthe desired level of accuracy.

EXAMPLE OF exit WI TH goto STATEMENT

Program

#def i ne LOOP 100#def i ne ACCURACY 0. 0001mai n( ){

Page 45: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 45/120

i nt n;f l oat x, t er m, sum;

pr i nt f ( " I nput val ue of x : " ) ;scanf ( "%f ", &x) ;sum = 0 ;f or ( t er m = 1, n = 1 ; n < = LOOP ; ++n){

sum += t er m ;i f ( t er m <= ACCURACY)

goto out put ; / * EXI T FROM THE LOOP */t er m *= x ;

}pr i nt f ( " \ nFI NAL VALUE OF N I S NOT SUFFI CI ENT\ n" ) ;pr i nt f ( " TO ACHI EVE DESI RED ACCURACY\ n") ;goto end;out put :pr i nt f ( "\ nEXI T FROM LOOP\ n") ;

pr i nt f ( " Sum = %f ; No. of t er ms = %d\ n" , sum, n) ;end:; / * Nul l St at ement */

}

Output

I nput val ue of x : . 21EXI T FROM LOOPSum = 1. 265800; No. of t er ms = 7

I nput val ue of x : . 75

EXI T FROM LOOPSum = 3. 999774; No. of t er ms = 34

I nput val ue of x : . 99FI NAL VALUE OF N I S NOT SUFFI CI ENT

TO ACHI EVE DESI RED ACCURACY

Fig.6.9 Use of goto to exit from a loop

Example 6.7

The program in Fig.6.11 illustrates the use of continue statement.

The program evaluates the square root of a series of numbers and prints the results. The process stops when the number 9999 is typed in.In case, the series contains any negative numbers, the process of evaluation of square rootshould be bypassed for such numbers because the square root of a negative number is notdefined. The continue statement is used to achieve this. The program also prints a messagesaying that the number is negative and keeps an account of negative numbers.

Page 46: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 46/120

The final output includes the number of positive values evaluated and the number of negativeitems encountered.

USE OF continue STATEMENT

Program:

#i ncl ude <mat h. h>

mai n( ){

i nt count , negat i ve;doubl e number , sqr oot ;

pr i nt f ( "Ent er 9999 t o STOP\ n" ) ;count = 0 ;negat i ve = 0 ;

whi l e ( count <= 100){

pr i nt f ( "Ent er a number : ") ;scanf ( " %l f " , &number ) ;i f ( number == 9999)

break; / * EXI T FROM THE LOOP */i f ( number < 0){

pr i nt f ( "Number i s negat i ve\ n\ n") ;negat i ve++ ;continue; / * SKI P REST OF THE LOOP */

}

sqroot = sqr t ( number ) ;pr i nt f ( " Number = %l f \ n Squar e r oot = %l f \ n\ n" ,number , sqr oot ) ;

count ++ ;}pr i nt f ( " Number of i t ems done = %d\ n" , count ) ;pr i nt f ( "\ n\ nNegat i ve i t ems = %d\ n" , negat i ve) ;pr i nt f ( " END OF DATA\ n" ) ;

}

Output

Ent er 9999 t o STOPEnt er a number : 25. 0

Page 47: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 47/120

Number = 25. 000000Squar e r oot = 5. 000000

Ent er a number : 40. 5Number = 40. 500000Squar e r oot = 6. 363961

Ent er a number : - 9Number i s negat i ve

Ent er a number : 16Number = 16. 000000Squar e r oot = 4. 000000

Ent er a number : - 14. 75Number i s negat i ve

Ent er a number : 80Number = 80. 000000Squar e r oot = 8. 944272

Ent er a number : 9999Number of i t ems done = 4Negat i ve i t ems = 2END OF DATA

_______________________________________________________________

Fig.6.11 Use of continue statement

Page 48: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 48/120

Example 7.1

Write a program using a single-subscripted variable to evaluate the following expressions:10

Total = x i

2

i=1

The values of x1,x2,....are read from the terminal.

Program in Fig.7.1 uses a one-dimensional array x to read the values and compute the sum oftheir squares.

PROGRAM SHOWI NG ONE-DIMENSIONAL ARRAY

Program :

mai n( ){

i nt i ;f l oat x[ 10] , val ue, t ot al ;

/ * . . . . . . READI NG VALUES I NTO ARRAY . . . . . . */

pr i nt f ( " ENTER 10 REAL NUMBERS\ n") ;

f or ( i = 0 ; i < 10 ; i ++ ){

scanf ( "%f ", &val ue) ;

x[ i ] = val ue ;}/ * . . . . . . . COMPUTATI ON OF TOTAL . . . . . . . * /

t ot al = 0. 0 ;f or ( i = 0 ; i < 10 ; i ++ )

t ot al = t ot al + x[ i ] * x[ i ] ;

/ *. . . . PRI NTI NG OF x[ i ] VALUES AND TOTAL . . . */

pr i nt f ( " \ n" ) ;f or ( i = 0 ; i < 10 ; i ++ )

pr i nt f ( "x[%2d] = %5. 2f \ n", i +1, x[ i ] ) ;pr i nt f ( " \ nt ot al = %. 2f \ n" , t ot al ) ;

}

Output ENTER 10 REAL NUMBERS1. 1 2. 2 3. 3 4. 4 5. 5 6. 6 7. 7 8. 8 9. 9 10. 10

Page 49: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 49/120

x[ 1] = 1. 10x[ 2] = 2. 20x[ 3] = 3. 30x[ 4] = 4. 40x[ 5] = 5. 50x[ 6] = 6. 60x[ 7] = 7. 70x[ 8] = 8. 80x[ 9] = 9. 90x[ 10] = 10. 10

Tot al = 446. 86

Fig.7.1 Program to illustrate one-dimensional array

Example 7.2

Given below is the list of marks obtained by a class of 50 students in an annual examination.

43 65 51 27 79 11 56 61 82 09 25 36 07 49 55 63 74 81 49 3740 49 16 75 87 91 33 24 58 78 65 56 76 67 45 54 36 63 12 2173 49 51 19 39 49 68 93 85 59

Write a program to count the number of students belonging to each of following groups ofmarks: 0-9, 10-19, 20-29,.....,100.

The program coded in Fig.7.2 uses the array group containing 11 elements, one for each rangeof marks. Each element counts those values falling within the range of values it represents.

For any value, we can determine the correct group element by dividing the value by 10. Forexample, consider the value 59. The integer division of 59 by 10 yields 5. This is the element intowhich 59 is counted.

PROGRAM FOR FREQUENCY COUNTING Program

#def i ne MAXVAL 50#def i ne COUNTER 11

mai n( ){

f l oat val ue[ MAXVAL] ;

i nt i , l ow, hi gh;i nt gr oup[ COUNTER] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

/ * . . . . . . . . READI NG AND COUNTI NG . . . . . . */f or ( i = 0 ; i < MAXVAL ; i ++ ){

/ * . . . . . . . . READI NG OF VALUES . . . . . . . . * /scanf ( "%f " , &val ue[ i ] ) ;

/ *. . . . . . COUNTI NG FREQUENCY OF GROUPS. . . . . */

Page 50: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 50/120

++ gr oup[ ( i nt ) ( val ue[ i ] + 0. 5 ) / 10] ;}

/ * . . . . PRI NTI NG OF FREQUENCY TABLE . . . . . . . */pr i nt f ( " \ n" ) ;pr i nt f ( " GROUP RANGE FREQUENCY\ n\ n") ;f or ( i = 0 ; i < COUNTER ; i ++ ){

l ow = i * 10 ;i f ( i == 10)

hi gh = 100 ;el se

hi gh = l ow + 9 ;pr i nt f ( " %2d %3d t o %3d %d\ n",

i +1, l ow, hi gh, gr oup[ i ] ) ;}

}

Output43 65 51 27 79 11 56 61 82 09 25 36 07 49 55 63 7481 49 37 40 49 16 75 87 91 33 24 58 78 65 56 76 6745 54 36 63 12 21 73 49 51 19 39 49 68 93 85 59

GROUP RANGE FREQUENCY1 0 t o 9 22 10 t o 19 43 20 t o 29 44 30 t o 39 55 40 t o 49 86 50 t o 59 87 60 t o 69 78 70 t o 79 69 80 t o 89 4

10 90 t o 99 211 100 t o 100 0

Fig.7.2 Program for frequency counting

Example 7.3Write a program using a two-dimensional array to compute and print the followinginformation from the table of data discussed above:

(a) Total value of sales by each girl.(b) Total value of each item sold.(c) Grand total of sales of all items by all girls.

(Input data)

Page 51: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 51/120

Page 52: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 52/120

{i t em_t ot al [ j ] = 0;f or ( i =0 ; i < MAXGI RLS ; i ++ )

i t em_ tot al [ j ] = i t em_ tot al [ j ] + val ue[ i ] [ j ] ;}

/ *. . . . . . . COMPUTI NG gr and_t ot al . . . . . . . . . . . . . . . . . . . . . . . . . * /

gr and_t ot al = 0;f or ( i =0 ; i < MAXGI RLS ; i ++ )

gr and_t ot al = gr and_t ot al + gi r l _t ot al [ i ] ;

/ * . . . . . . . PRI NTI NG OF RESULTS. . . . . . . . . . . . . . . . . . . . . . . . . . . * /

pr i nt f ( "\ n GI RLS TOTALS\ n\ n") ;f or ( i = 0 ; i < MAXGI RLS ; i ++ )

pr i nt f ( "Sal esgi r l [ %d] = %d\ n" , i +1, gi r l _ tot al [ i ] ) ;

pr i nt f ( " \ n I TEM TOTALS\ n\ n") ;f or ( j = 0 ; j < MAXI TEMS ; j ++ )pr i nt f ( "I t em[ %d] = %d\ n", j +1 , i t em_t ot al [ j ] ) ;

pr i nt f ( "\ nGr and Tot al = %d\ n", gr and_t ot al ) ;}

Output

I nput dat aEnt er val ues, one at a t i me, r ow_wi se

310 257 365

210 190 325405 235 240260 300 380

GI RLS TOTALS

Sal esgi r l [ 1] = 950Sal esgi r l [ 2] = 725Sal esgi r l [ 3] = 880Sal esgi r l [ 4] = 940

I TEM TOTALS

I t em[ 1] = 1185I t em[ 2] = 1000I t em[ 3] = 1310

Gr and Tot al = 3495

Fig.7.4 Illustration of two-dimensional arrays.

Page 53: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 53/120

Example 7.4Write a program to compute and print a multiplication table for numbers 1 to 5 asshown below:

1 2 3 4 5

1 1 2 3 4 5

2 2 4 6 8 103 3 6 . . .

4 4 8 . . .

5 5 10 . . 25

The program shown in Fig.7.5 uses a two-dimensional array to store the table values.Each value is calculated using the control variables of the nested for loops as follows:

produc t(i,j) = row * column

where i denotes rows and j denotes columns of the product table. Since the indices i and j

ranges from 0 to 4, we have introduced the following transformation:row = i+1column = j+1

PROGRAM TO PRI NT MULTI PLI CATI ON TABLE

Program: #def i ne ROWS 5#def i ne COLUMNS 5mai n( ){ i nt r ow, col umn, pr oduct [ ROWS] [ COLUMNS] ;

i nt i , j ;

pr i nt f ( " MULTI PLI CATI ON TABLE\ n\ n" ) ;pr i nt f ( " " ) ;

f or ( j = 1 ; j <= COLUMNS ; j ++ )pr i nt f ( " %4d" , j ) ;

pr i nt f ( " \ n" ) ;pr i nt f ( " - - - - - - - - - - - - - - - - - - - - - - - - - \ n" ) ;f or ( i = 0 ; i < ROWS ; i ++ ){

r ow = i + 1 ;

pr i nt f ( "%2d | " , r ow) ;f or ( j = 1 ; j <= COLUMNS ; j ++ )

{ col umn = j ; pr oduct [ i ] [ j ] = r ow * col umn ;pr i nt f ( "%4d" , pr oduct [ i ] [ j ] ) ;

}pr i nt f ( " \ n" ) ;

}}

Page 54: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 54/120

Page 55: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 55/120

char c i t y;

pr i nt f ( "For each per son, ent er t he ci t y code \ n") ;pr i nt f ( "f ol l owed by t he car code. \ n") ;pr i nt f ( "Ent er t he l et t er X t o i ndi cat e end. \ n") ;

/ * . . . . . . TABULATI ON BEGI NS . . . . . * /

f or ( i = 1 ; i < 100 ; i ++ ){

scanf ( "%c", &ci t y ) ;i f ( ci t y == ' X' )

br eak;

scanf ( "%d", &car ) ;

swi t ch( ci t y){

case ' B' : f r equency[ 1] [ car ] ++;br eak;case ' C' : f r equency[ 2] [ car ] ++;

br eak;case ' D' : f r equency[ 3] [ car ] ++;

br eak;case ' M' : f r equency[ 4] [ car ] ++;

br eak;}

}

/ *. . . . . TABULATI ON COMPLETED AND PRI NTI NG BEGI NS. . . . */

pr i nt f ( " \ n\ n" ) ;pr i nt f ( " POPULARI TY TABLE\ n\ n" ) ;pr i nt f ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n" ) ;pr i nt f ( "Ci t y Ambassador Fi at Dol phi n Mar ut i \ n") ;pr i nt f ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n" ) ;f or ( i = 1 ; i <= 4 ; i ++ ){

Page 56: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 56/120

swi t ch( i ){

case 1 : pr i nt f ( " Bombay " ) ;br eak ;

case 2 : pr i nt f ( "Cal cut t a " ) ;br eak ;

case 3 : pr i nt f ( "Del hi " ) ;br eak ;

case 4 : pr i nt f ( "Madr as ") ;br eak ;

}f or ( j = 1 ; j <= 4 ; j ++ )

pr i nt f ( "%7d" , f r equency[ i ] [ j ] ) ;pr i nt f ( " \ n" ) ;

}pr i nt f ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n" ) ;

/ *. . . . . . . . . PRI NTI NG ENDS. . . . . . . . . . . * /

}Output

For each per son, ent er t he ci t y codef ol l owed by t he car code.Ent er t he l et t er X t o i ndi cat e end.

M 1 C 2 B 1 D 3 M 2 B 4C 1 D 3 M 4 B 2 D 1 C 3D 4 D 4 M 1 M 1 B 3 B 3C 1 C 1 C 2 M 4 M 4 C 2

D 1 C 2 B 3 M 1 B 1 C 2D 3 M 4 C 1 D 2 M 3 B 4 X

POPULARI TY TABLE- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Ci t y Ambassador Fi at Dol phi n Mar ut i- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Bombay 2 1 3 2Cal cut t a 4 5 1 0Del hi 2 1 3 2Madr as 4 1 1 4- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Fig.7.6 Program to tabulate a survey data

Page 57: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 57/120

Example 8.1

Write a program to read a series of words from a terminal using scanf function

The program shown in Fig.8.1 reads four words and displays them on the screen. Note that thestring 'Oxford Road' is treated as two words while the string 'Oxford-Road' as one word.

READI NG A SERI ES OF WORDS USI NG scanf FUNCTI ON

Program

mai n( ){

char word1[ 40] , wor d2[ 40] , wor d3[ 40] , wor d4[ 40] ;

pr i nt f ( " Ent er t ext : \ n" ) ;scanf ( " %s %s" , word1, wor d2) ;scanf ( " %s" , wor d3) ;scanf ( " %s" , wor d4) ;

pr i nt f ( " \ n" ) ;pr i nt f ( " wor d1 = %s\ nwor d2 = %s\ n", wor d1, wor d2) ;pr i nt f ( " wor d3 = %s\ nwor d4 = %s\ n" , wor d3, wor d4) ;

}

Output

Ent er t ext :Oxf or d Road, London M17ED

wor d1 = Oxf or dwor d2 = Road,wor d3 = London

wor d4 = M17EDEnt er t ext :Oxf or d- Road, London- M17ED Uni t ed Ki ngdomwor d1 = Oxf or d- Roadwor d2 = London- M17EDwor d3 = Uni t edwor d4 = Ki ngdom

Fig.8.1 Reading a series of words using scanf

Example 8.2Write a program to read a line of text containing a series of words from the terminal.

The program shown in Fig.8.2 can read a line of text (upto a maximum of 80 characters) into thestring line using getchar function. Every time a character is read, it is assigned to its location inthe string line and then tested for newline character. When the newline character is read(signalling the end of line), the reading loop is terminated and the newline character is replacedby the null character to indicate the end of character string.

When the loop is exited, the value of the index c is one number higher than the last characterposition in the string (since it has been incremented after assigning the new character to the

Page 58: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 58/120

string). Therefore the index value c-1 gives the position where the null character is to be stored.

PROGRAM TO READ A LINE OF TEXT FROM TERMI NAL

Program

#i ncl ude <st di o. h>

mai n( ){

char l i ne[ 81] , char acter ;i nt c;

c = 0;

pr i nt f ( "Ent er t ext . Pr ess <Ret ur n> at end\ n") ;do{

char act er = get char ( ) ;l i ne[ c] = char acter ;c++;

}whi l e( char ac ter ! = ' \ n' ) ;

c = c - 1;l i ne[ c] = ' \ 0' ;pr i nt f ( " \ n%s \ n" , l i ne) ;

}

Output

Ent er t ext . Pr ess <Ret ur n> at endPr ogr ammi ng i n C i s i nt er est i ng.

Pr ogr ammi ng i n C i s i nt er est i ng.Ent er t ext . Pr ess <Ret ur n> at endNat i onal Cent r e f or Exper t Syst ems, Hyderabad.

Nat i onal Cent r e f or Exper t Syst ems, Hyderabad.

Fig.8.2 Program to read a line of text from terminal

Example 8.3Write a program to copy one string into another and count the number of characters copied.

The program is shown in Fig.8.3. We use a fo r loop to copy the characters contained inside string2 into the string1 . The loop is terminated when the null character is reached. Note that weare again assigning a null character to the string1.

COPYING ONE STRING I NTO ANOTHER

Program

mai n( ){

char s t r i ng1[ 80] , s t r i ng2[ 80] ;

Page 59: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 59/120

i nt i ;

pr i nt f ( "Ent er a s t r i ng \ n" ) ;pr i nt f ( " ? ") ;

scanf ( "%s", s t r i ng2) ;

f or ( i =0 ; s t r i ng2[ i ] ! = ' \ 0' ; i ++)s t r i ng1[ i ] = s t r i ng2[ i ] ;

s t r i ng1[ i ] = ' \ 0' ;

pr i nt f ( " \ n" ) ;pr i nt f ( "%s \ n" , s t r i ng1) ;pr i nt f ( "Number of char act er s = %d\ n", i ) ;

}

Output

Ent er a st r i ng?Manchest er

Manchest erNumber of char act er s = 10

Ent er a st r i ng?West mi nst er

West mi nst erNumber of char act er s = 11

Fig.8.3 Copying one string into another

Example 8.4Write a program to store the string "United Kingdom" in the array country and display the stringunder various format specifications.

The program and its output are shown in Fig.8.4. The output illustrates the following features ofthe %s specifications.

1. When the field width is less than the length of the string, the entire string is printed.

2. The integer value on the right side of the decimal point specifies the number ofcharacters to be printed.

3. When the number of characters to be printed is specified as zero, nothing is printed.

4. The minus sign in the specification causes the string to be printed left-justified.

5. The specification % .ns prints the first n characters of the string

WRITING STRI NGS USI NG %s FORMAT

Page 60: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 60/120

Program

mai n( ){

char count r y[ 15] = " Uni t ed Ki ngdom" ;

pr i nt f ( " \ n\ n" ) ;pr i nt f ( " *123456789012345*\ n" ) ;pr i nt f ( " - - - - - - - - - - - - - - - \ n" ) ;

pr i nt f ( "%15s\ n", count r y) ;pr i nt f ( "%5s\ n", count r y) ;pr i nt f ( "%15. 6s\ n", count r y) ;pr i nt f ( "%- 15. 6s \ n" , count r y) ;pr i nt f ( "%15. 0s\ n", count r y) ;pr i nt f ( "%. 3s \ n" , count r y) ;pr i nt f ( "%s\ n" , count r y) ;pr i nt f ( " - - - - - - - - - - - - - - - - \ n" ) ;

}

Output

*123456789012345*- - - - - - - - - - - - - - - - - -

Uni t ed Ki ngdomUni t ed Ki ngdom

Uni t edUni t ed

UniUni t ed Ki ngdom

- - - - - - - - - - - - - - - - - -

Fig.8.4 Writing strings using %s format

Page 61: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 61/120

Page 62: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 62/120

Output

Fig.8.5 Illustration of variable field specifications

Example 8.6

Write a program which would print the alphabet set a to z and A to Z in decimal and characterform.

The program is shown in Fig.8.7. In ASCII character set, the decimal numbers 65 to 90 representuppercase alphabets and 97 to 122 represent lowercase alphabets. The values from 91 to 96 areexcluded using an if statement in the for loop.

PRI NTI NG ALPHABET SET I N DECI MAL AND CHARACTER FORM

Program

mai n( ){

char c;

pr i nt f ( " \ n\ n" ) ;f or ( c = 65 ; c <= 122 ; c = c + 1 ){

i f ( c > 90 && c < 97 )cont i nue;

CCPCPrCProCProgCProgrCPrograCProgramCProgrammCProgrammiCProgramminCProgramming

CProgrammingCProgramminCProgrammiCProgramm

CProgramCPrograCProgrCProgCProCPrCPC

Page 63: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 63/120

pr i nt f ( " | %4d - %c " , c , c ) ;}pr i nt f ( " | \ n" ) ;

}

Output

| 65 - A | 66 - B | 67 - C | 68 - D | 69 - E | 70 - F| 71 - G | 72 - H | 73 - I | 74 - J | 75 - K | 76 - L| 77 - M | 78 - N | 79 - O | 80 - P | 81 - Q | 82 - R| 83 - S | 84 - T | 85 - U | 86 - V | 87 - W | 88 - X| 89 - Y | 90 - Z | 97 - a | 98 - b | 99 - c | 100 - d| 101 - e | 102 - f | 103 - g | 104 - h | 105 - i | 106 - j| 107 - k | 108 - l | 109 - m | 110 - n | 111 - o | 112 - p| 113 - q | 114 - r | 115 - s | 116 - t | 117 - u | 118 - v| 119 - w | 120 - x | 121 - y | 122 - z |

Fig.8.7 Printing of the alphabet set in decimal and character form

Example 8.7

The names of employees of an organization are stored in three arrays, namely first_name ,second_name, and last_name . Write a program to concatenate the three parts into onestring to be called name .

The program is given in Fig.8.8. Three for loops are used to copy the three strings. In the firstloop, the characters contained in the first_name are copied into the variable name until the null character is reached. The null character is not copied; instead it is replaced by a space by theassignment statement

name[i] = \ / ;

Similarly, the second_name is copied into name , starting from the column just after the spacecreated by the above statement. This is achieved by the assignment statement

name[i+j+1] = second_name[j];

If first_name contains 4 characters, then the value of i at this point will be 4 and therefore the firstcharacter from second_name will be placed in the fifth cell of name. Note that we have stored aspace in the fourth cell .

In the same way, the statement

name[i+j+k+2] = last_name[k];

is used to copy the characters from last_name into the proper locations of name. At the end, we place a null character to terminate the concatenated string name . In this example,it is important to note the use of the expressions i+j+1 and i+j+k+2.

Page 64: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 64/120

CONCATENATI ON OF STRI NGS

Program

mai n( ){

i nt i , j , k ;char f i r st _name[ 10] = {"VI SWANATH" } ;char second_name[ 10] = {"PRATAP"} ;char l ast _name[ 10] = {"SI NGH" } ;char name[ 30] ;

/ * Copy f i r st _name i nt o name */

f or ( i = 0 ; f i r s t_name[ i ] ! = ' \ 0' ; i ++ )name[ i ] = f i r st _name[ i ] ;

/ * End f i r st _name wi t h a space */

name[ i ] = ' ' ;

/ * Copy second_name i nt o name */

f or ( j = 0 ; second_name[ j ] ! = ' \ 0' ; j ++ )name[ i +j +1] = second_name[ j ] ;

/ * End second_name wi t h a space */

name[ i +j +1] = ' ' ;

/ * Copy l ast _name i nt o name */

f or ( k = 0 ; l ast _name[ k] ! = ' \ 0' ; k++ )name[ i +j +k+2] = l ast _name[ k] ;

/ * End name wi t h a nul l char act er */

name[ i +j +k+2] = ' \ 0' ;

pr i nt f ( " \ n\ n" ) ;pr i nt f ( "%s\ n", name) ;

}

OutputVI SWANATH PRATAP SI NGH

Fig.8.8 Concatenation of strings

Example 8.8

s1, s2, and s3 are three string variables. Write a program to read two string constants into s1 and s2 and compare whether they are equal or not. If they are not, join them together. Thencopy the contents of s1 to the variable s3 . At the end, the program should print the contents ofall the three variables and their lengths.

Page 65: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 65/120

The program is shown in Fig.8.9. During the first run, the input strings are "New" and"York". These strings are compared by the statement

x = strcmp(s1, s2);

Since they are not equal, they are joined together and copied into s3 using the statement

strcpy(s3, s1);

The program outputs all the three strings with their lengths.

During the second run, the two strings s1 and s2 are equal, and therefore, they are not joinedtogether. In this case all the three strings contain the same string constant "London".

Page 66: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 66/120

I LLUSTRATI ONS OF STRI NG- HANDLI NG FUNCTI ONS

Program

#i ncl ude <st r i ng. h>

mai n( ){ char s1[ 20] , s2[ 20] , s3[ 20] ;

i nt x, l 1, l 2, l 3;

pr i nt f ( " \ n\ nEnt er t wo st r i ng const ant s \ n") ;pr i nt f ( " ? ") ;scanf ( " %s %s" , s1, s2) ;

/ * compar i ng s1 and s2 */

x = st r cmp( s1, s2) ;i f ( x ! = 0){ pr i nt f ( " \ n\ nSt r i ngs ar e not equal \ n" ) ;

s t r cat ( s1, s2) ; / * j oi ni ng s1 and s2 * /}el se

pr i nt f ( " \ n\ nSt r i ngs ar e equal \ n" ) ;

/ * copyi ng s1 t o s3

s t r cpy( s3, s1) ;

/ * Fi ndi ng l engt h of s t r i ngs * /

l 1 = s t r l en( s1) ;l 2 = s t r l en( s2) ;l 3 = s t r l en( s3) ;

/ * out put */

pr i nt f ( "\ ns1 = %s\ t l engt h = %d char act er s\ n", s1, l 1) ;pr i nt f ( " s2 = %s\ t l engt h = %d char act er s\ n", s2, l 2) ;pr i nt f ( " s3 = %s\ t l engt h = %d char act er s\ n", s3, l 3) ;

}

Page 67: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 67/120

O utput

Ent er t wo st r i ng const ant s? New Yor k

St r i ngs are not equal

s1 = NewYor k l engt h = 7 char act er ss2 = Yor k l engt h = 4 char act er ss3 = NewYor k l engt h = 7 char act er s

Ent er t wo st r i ng const ant s? London London

St r i ngs ar e equal

s1 = London l engt h = 6 char act er ss2 = London l engt h = 6 char act er ss3 = London l engt h = 6 char act er s

Fig.7.9 Illustration of string handling functions

Example 8.9

Write a program that would sort a list of names in alphabetical order.

A program to sort the list of strings in alphabetical order is given in Fig.8.10. It employs themethod of bubble sorting described in Case Study 1 in the previous chapter.

SORTI NG OF STRI NGS I N ALPHABETI CAL ORDER

Program

#def i ne I TEMS 5#def i ne MAXCHAR 20

mai n( ){

char st r i ng[ I TEMS] [ MAXCHAR] , dummy[ MAXCHAR] ; i nt i = 0, j = 0;

/ * Readi ng t he l i s t * /

pr i nt f ( " Ent er names of %d i t ems \ n " , I TEMS) ;whi l e ( i < I TEMS)scanf ( "%s", s t r i ng[ i ++] ) ;

/ * Sor t i ng begi ns */

f or ( i =1; i < I TEMS; i ++) / * Out er l oop begi ns */{

f or ( j =1; j <= I TEMS- i ; j ++) / *I nner l oop begi ns*/ {

Page 68: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 68/120

i f ( s t r cmp ( s t r i ng[ j - 1] , s t r i ng[ j ] ) > 0){ / * Exchange of cont ent s * /

st r cpy ( dummy, st r i ng[ j - 1] ) ;st r cpy ( s t r i ng[ j - 1] , st r i ng[ j ] ) ;st r cpy ( st r i ng[ j ] , dummy ) ;

}

} / * I nner l oop ends */

} / * Out er l oop ends */

/ * Sor t i ng compl et ed */

pr i nt f ( " \ nAl phabet i cal l i s t \ n\ n" ) ;f or ( i =0; i < I TEMS ; i ++)

pr i nt f ( " %s ", s t r i ng[ i ] ) ;}

Output

Ent er names of 5 i t ems

London Manchest er Del hi Par i s MoscowAl phabet i cal l i s t

Del hiLondonManchest erMos cowPar i s

Fig.8.10 Sorting of strings.

Page 69: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 69/120

Example 9.1

Write a program with multiple functions that do not communicate any data between them.

A program with three user-defined functions is given in Fig.9.4. main is the calling function that

calls printline and value functions. Since both the called functions contain no arguments, thereare no argument declarations. The printline function, when encountered, prints a line with alength of 35 characters as prescribed in the function. The value function calculates the value ofprincipal amount after a certain period of years and prints the results. The following equation isevaluated repeatedly:

value = principal(1+interest-rate)

Page 70: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 70/120

FUNCTI ONS WI TH THE ARGUMENTS, NO RETURN VALUES

Program

/ * Funct i on decl ar at i on */voi d pr i nt l i ne ( voi d) ;

voi d val ue (voi d) ;mai n( ){

pr i nt l i ne( ) ;val ue( ) ;pr i nt l i ne( ) ;

}

/ * Funct i on1: pr i nt l i ne( ) * /

voi d pr i nt l i ne( voi d) / * cont ai ns no ar gument s */{

i nt i ;

f or ( i =1; i <= 35; i ++)pr i nt f ( " %c" , ' - ' ) ;

pr i nt f ( " \ n" ) ;}

/ * Funct i on2: val ue( ) */

voi d val ue( voi d) / * cont ai ns no ar gument s */{

i nt year , per i od;f l oat i nr at e, sum, pr i nc i pal ;

pr i nt f ( "Pri nci pal amount ?") ;scanf ( "%f ", &pr i nci pal ) ;pr i nt f ( " I nt er es t r at e? " ) ;scanf ( "%f ", &i nr at e) ;pr i nt f ( " Per i od? " ) ;scanf ( " %d", &per i od) ;

sum = pr i nci pal ;year = 1;whi l e( year <= per i od){

sum = sum *( 1+i nr at e) ;

year = year +1;}pr i nt f ( " \ n%8. 2f %5. 2f %5d %12. 2f \ n" ,

pr i nci pal , i nr at e, per i od, sum) ;}

Page 71: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 71/120

Output-----------------------------------

Pr i nci pal amount ? 5000I nt er est r at e? 0. 12Per i od? 5

5000. 00 0. 12 5 8811. 71------------------------------------

Fig.9.4 Functions with no arguments and no return values

Example 9.2

Modify the program of Example 9.1 to include the arguments in the function calls.

The modified program with function arguments is presented in Fig.9.7. Most of the program isidentical to the program in Fig.9.4. The input prompt and scanf assignment statement have beenmoved from value function to main. The variables princip al, inrate, and period are declared inmain because they are used in main to receive data. The function call

value(principal, inrate, period);

passes information it contains to the function value.

The function header of value has three formal arguments p,r, and n which correspond to theactual arguments in the function call, namely, principal, inrate, and period. On execution of thefunction call, the values of the actual arguments are assigned to the corresponding formalarguments. In fact, the following assignments are accomplished across the function boundaries:

p = principal;r = inrate;n = period;

FUNCTI ONS WI TH ARGUMENTS BUT NO RETURN VALUES

Program

/ * pr ot ot ypes */voi d pr i nt l i ne ( char c ) ;voi d val ue ( f l oat , f l oat , i nt ) ;

mai n( ){

f l oat pr i nci pal , i nr at e;

i nt per i od;

pr i nt f ( "Ent er pr i nci pal amount , i nt er est ") ;pr i nt f ( " r at e, and per i od \ n") ;scanf ( "%f %f %d" , &pr i nci pal , &i nr at e, &per i od) ;pr i nt l i ne( ' Z' ) ;val ue( pr i nc i pal , i nr at e, per i od) ;pr i nt l i ne( ' C' ) ;

}

Page 72: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 72/120

voi d pr i nt l i ne( char ch){

i nt i ;f or ( i =1; i <= 52; i ++)

pr i nt f ( "%c" , ch) ;pr i nt f ( " \ n" ) ;

}

voi d val ue( f l oat p, f l oat r , i nt n){

i nt year ;f l oat s um ;sum = p ;year = 1;whi l e( year <= n){

sum = sum * ( 1+r ) ;year = year +1;

}pr i nt f ( "%f \ t %f \ t %d\ t %f \ n", p, r , n, sum) ;

}

Output

Ent er pr i nci pal amount , i nt er est r at e, and per i od5000 0. 12 5

ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ5000. 000000 0. 120000 5 8811. 708984CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

Fig.9.7 Functions with arguments but no return values

Example 9.3In the program presented in Fig. 9.7 modify the function value, to return the final amountcalculated to the main , which will display the required output at the terminal. Also extend theversatility of the function printline by having it to take the length of the line as an argument.

The modified program with the proposed changes is presented in Fig. 9.9. One major change isthe movement of the printf statement from value to main.

FUNCTI ONS WI TH ARGUMENTS AND RETURN VALUES

Program

voi d pr i nt l i ne ( char ch, i nt l en) ;

Page 73: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 73/120

Page 74: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 74/120

Example 9.4

Write a function power that computes x raised to the power y for integers x and y and returnsdouble-type value.

Fig 9.10 shows a power function that returns a double. The prototype declaration

double pow er(int, int);appears in main , before power is called.

POWER FUNCTI ONS

Program

mai n( ){ i nt x, y; / * i nput dat a * /

doubl e power ( i nt , i nt ) ; / * pr ot ot ype decl ar at i on*/

pr i nt f ( “ Ent er x, y: ” ) ;

scanf ( “%d %d” , &x, &y) ;pr i nt f ( “%d t o power %d i s %f \ n”, x, y, power ( x, y) ) ;

}

doubl e power ( i nt x, i nt y) ;

{doubl e p;p = 1. 0 ; / * x t o power zer o */

i f ( y >=o)whi l e( y- - ) / * comput es posi t i ve power s */

p *= x;el se

whi l e ( y++) / * comput es negat i ve power s */p / = x;

r et ur n( p) ;

}

Output

Ent er x, y: 16 2

16 t o power 2 i s 256. 000000

Ent er x, y: 16 - 2 16 t o power - 2 i s 0. 003906

Fig 9.10 Illustration of return of float values

Example 9.5

Page 75: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 75/120

Write a program to calculate the standard deviation of an array of values. The arrayelements are read from the terminal. Use functions to calculate standard deviation andmean.

Standard deviation of a set of n values is given by

S.D = --- ∑ ( x -x i )2

Where x is the mean of the values.

FUNCTI ONS WI TH ARRAYS

Program

#i ncl ude <mat h. h>#def i ne SI ZE 5f l oat s t d_dev( f l oat a[ ] , i nt n) ;f l oat mean ( f l oat a[ ] , i nt n) ;

mai n( ){

f l oat val ue[ SI ZE] ;i nt i ;

pr i nt f ( "Ent er %d f l oat val ues\ n", SI ZE) ;f or ( i =0 ; i < SI ZE ; i ++)

scanf ( "%f ", &val ue[ i ] ) ;pr i nt f ( "St d. devi at i on i s %f \ n", s t d_dev( val ue, SI ZE) ) ;

}

f l oat s t d_dev( f l oat a[ ] , i nt n)

{ i nt i ; f l oat x, sum = 0. 0;x = mean ( a, n) ;f or ( i =0; i < n; i ++)

sum += ( x- a[ i ] ) * (x -a[ i ] ) ;r et ur n( sqr t ( sum/ ( f l oat ) n) ) ;

}

f l oat mean( f l oat a[ ] , i nt n){

i nt i ;f l oat sum = 0. 0;f or ( i =0 ; i < n ; i ++)

sum = sum + a[ i ] ;r et ur n( sum/ ( f l oat ) n) ;

}

n

i=1

1n

Page 76: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 76/120

Output Ent er 5 f l oat val ues35. 0 67. 0 79. 5 14. 20 55. 75

St d. devi at i on i s 23. 231582

Fig.9.11 Passing of arrays to a function

Example 9.6

Write a program that uses a function to sort an array of integers.

A program to sort an array of integers using the function sort() is given in Fig.9.12. Its outputclearly shows that a function can change the values in an array passed as an argument.

SORTI NG OF ARRAY ELEMENTS

Program

voi d sor t ( i nt m, i nt x[ ] ) ;mai n( ){

i nt i ;i nt mar ks[ 5] = {40, 90, 73, 81, 35};

pr i nt f ( "Mar ks bef or e sor t i ng\ n") ;f or ( i = 0; i < 5; i ++)

pr i nt f ( "%d " , mar ks[ i ] ) ;pr i nt f ( " \ n\ n" ) ;

sor t ( 5, mar ks) ;

pr i nt f ( "Mar ks af t er sor t i ng\ n") ;f or ( i = 0; i < 5; i ++)

pr i nt f ( "%4d", mar ks[ i ] ) ;pr i nt f ( " \ n" ) ;

}

voi d sor t ( i nt m, i nt x[ ] )

{i nt i , j , t ;

Page 77: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 77/120

f or ( i = 1; i <= m- 1; i ++)f or ( j = 1; j <= m- i ; j ++)

i f ( x[ j - 1] >= x[ j ] ){

t = x[ j - 1] ;x[ j - 1] = x[ j ] ;x[ j ] = t ;

}}

OutputMar ks bef or e sor t i ng40 90 73 81 35

Mar ks af t er sor t i ng35 40 73 81 90

Fig.9.12 Sorting of array elements using a function

Example 9.7

Write a multifunction to illustrate how automatic variables work.

A program with two subprograms function1 and function2 is shown in Fig.9.13. m is anautomatic variable and it is declared at the beginning of each function. m is initialized to 10, 100,and 1000 in function1, function2, and main respectively.

When executed, main calls function2 which in turn calls function1 . When main is active, m =1000; but when function2 is called, the main 's m is temporarily put on the shelf and the newlocal m = 100 becomes active. Similarly, when function1 is called, both the previous values of m are put on the shelf and the latest value of m (=10) becomes active. As soon as function1 (m=10) is finished, function2 (m=100) takes over again. As soon it is done, main (m=1000)takes over. The output clearly shows that the value assigned to m in one function does not affectits value in the other functions; and the local value of m is destroyed when it leaves a function.

I LLUSTRATI ON OF WORKI NG OF auto VARI ABLES

Program

voi d f unct i on1( voi d) ;voi d f unct i on2( voi d) ;mai n( )

Page 78: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 78/120

{i nt m = 1000;f unct i on2( ) ;

pr i nt f ( "%d\ n", m) ; / * Thi r d out put */}voi d f unct i on1( voi d){

i nt m = 10;

pr i nt f ( "%d\ n" , m) ; / * Fi r s t out put */}

voi d f unct i on2( voi d){

i nt m = 100;

f unct i on1( ) ;pr i nt f ( " %d\ n" , m) ; / * Second out put */

}

Output 101001000

Fig.9.13 Working of automatic variables

Example 9.8

Write a multifunction program to illustrate the properties of global variables.

A program to illustrate the properties of global variables is presented in Fig.9.14. Note thatvariable x is used in all functions but none except fun2, has a definition for x. Because x hasbeen declared 'above' all the functions, it is available to each function without having to pass x asa function argument. Further, since the value of x is directly available, we need not use return(x) statements in fun1 and fun3. However, since fun2 has a definition of x, it returns its local valueof x and therefore uses a return statement. In fun2 , the global x is not visible. The local x hidesits visibility here.

I LLUSTRATI ON OF PROPERTI ES OF GLOBAL VARI ABLESProgram

i nt f un1( voi d) ;i nt f un2( voi d) ;i nt f un3( voi d) ; i nt x ; / * gl obal * /mai n( )

Page 79: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 79/120

{x = 10 ; / * gl obal x */pr i nt f ( "x = %d\ n", x) ;pr i nt f ( "x = %d\ n", f un1( ) ) ;pr i nt f ( "x = %d\ n", f un2( ) ) ;pr i nt f ( "x = %d\ n", f un3( ) ) ;

}f un1( voi d){

x = x + 10 ;}i nt f un2( voi d){

i nt x ; / * l ocal * /x = 1 ;r et ur n ( x) ;

}f un3( voi d)

{ x = x + 10 ; / * gl obal x */}

Output x = 10x = 20x = 1x = 30

Fig.9.14 Illustration of global variables

Example 9.9

Write a program to illustrate the properties of a static variable.

The program in Fig.9.15 explains the behaviour of a static variable.

I LLUSTRATI ON OF STATI C VARI ABLE

Program

voi d s ta t ( voi d) ;mai n ( ){

i nt i ;f or ( i =1; i <=3; i ++)s t a t ( ) ;

}voi d s t at ( voi d){

Page 80: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 80/120

s t at i c i nt x = 0;

x = x+1;pr i nt f ( "x = %d\ n", x) ;

}

Outputx = 1x = 2x = 3

Fig.9.15 Illustration of static variable

Page 81: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 81/120

Example 10.1

Define a structure type, struct personal that would contain person name, date of joining andsalary. Using this structure, write a program to read this information for one person from thekeyboard and print the same on the screen.

Structure definition along with the program is shown in Fig.10.1. The scanf and printf functionsillustrate how the member operator `.' is used to link the structure members to the structurevariables. The variable name with a period and the member name is used like an ordinaryvariable.

DEFI NI NG AND ASSI GNI NG VALUES TO STRUCTURE MEMBERS

Program st r uct per sonal{

char name[ 20] ;i nt day;char mont h[ 10] ;i nt year ;

f l oat s al ar y ;};mai n( ){

st r uct per sonal per son;pr i nt f ( " I nput Val ues \ n") ;scanf ( " %s %d %s %d %f " ,

per son. name,&per son. day,

per son. mont h,&per son. year ,&per son. sal ar y) ;

pr i nt f ( " %s %d %s %d %f \ n",per son. name,per son. day,per son. mont h,per son. year ,per son. sal ar y) ;

}

Page 82: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 82/120

Output

I nput Val ues

M. L. Goel 10 J anuar y 1945 4500M. L. Goel 10 J anuar y 1945 4500. 00

Fig.10.1 Defining and accessing structure members

Example 10.2

Write a program to illustrate the comparison of structure variables.

The program shown in Fig.10.2 illustrates how a structure variable can be copied into another ofthe same type. It also performs member-wise comparison to decide whether two structurevariables are identical.

COMPARI SON OF STRUCTURE VARI ABLES

Program

s t r uc t c l ass{

i nt number ;char name[ 20] ;f l oat mar ks;

};mai n( ){

i nt x;st r uct cl ass st udent 1 = {111, " Rao" , 72. 50};st r uct cl ass s t udent 2 = {222, " Reddy", 67. 00};st r uct cl ass st udent 3;

st udent 3 = st udent 2;

x = ( ( st udent 3. number == st udent 2. number ) &&( st udent 3. marks == st udent 2. mar ks) ) ? 1 : 0;

i f ( x == 1){

pr i nt f ( "\ nst udent 2 and st udent 3 ar e same\ n\ n" ) ;pr i nt f ( " %d %s %f \ n" , st udent 3. number ,

st udent 3. name,st udent 3. mar ks) ;

}

Page 83: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 83/120

el sepr i nt f ( "\ nst udent 2 and st udent 3 ar e di f f er ent \ n\ n") ;

}

Output

st udent 2 and st udent 3 ar e same

222 Reddy 67. 000000

Fig.10.2 Comparing and copying structure variables

Example 10.3

For the student array discussed above, write a program to calculate the subject-wise andstudent-wise totals and store them as a part of the structure.

The program is shown in Fig.10.4. We have declared a four-member structure, the fourth one forkeeping the student-totals. We have also declared an array total to keep the subject-totals andthe grand-total. The grand-total is given by total.total. Note that a member name can be anyvalid C name and can be the same as an existing structure variable name. The linked nametotal.total represents the total member of the structure variable total.

ARRAYS OF STRUCTURES

Program

st r uct mar ks{

i nt sub1;i nt sub2;i nt sub3;i nt t ot al ;

};mai n( ){

i nt i ;st r uct marks st udent [ 3] = {{45, 67, 81, 0},

{75, 53, 69, 0},{57, 36, 71, 0}};

st r uct mar ks t ot al ;

f or ( i = 0; i <= 2; i ++){

st udent [ i ] . t ot al = st udent [ i ] . sub1 +st udent [ i ] . sub2 +st udent [ i ] . sub3;

t ot al . sub1 = t ot al . sub1 + st udent [ i ] . sub1;t ot al . sub2 = t ot al . sub2 + st udent [ i ] . sub2;t ot al . sub3 = t ot al . sub3 + st udent [ i ] . sub3;t ot al . t ot al = t ot al . t ot al + s t udent [ i ] . t ot al ;

Page 84: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 84/120

}pr i nt f ( " STUDENT TOTAL\ n\ n" ) ;f or ( i = 0; i <= 2; i ++)

pr i nt f ( "St udent [ %d] %d\ n", i +1, s t udent [ i ] . t ot al ) ;

pr i nt f ( "\ n SUBJ ECT TOTAL\ n\ n") ;

pr i nt f ( " %s %d\ n%s %d\ n%s %d\ n" ,"Subj ect 1 " , t ot al . sub1,"Subj ect 2 " , t ot al . sub2,"Subj ect 3 " , t ot al . sub3) ;

pr i nt f ( " \ nGr and Tot al = %d\ n", t ot al . t ot al ) ;}

Output

STUDENT TOTALSt udent [ 1] 193

St udent [ 2] 197St udent [ 3] 164

SUBJ ECT TOTALSubj ect 1 177Subj ect 2 156Subj ect 3 221

Gr and Tot al = 554

Fig.10.4 Illustration of subscripted structure variables

Example 10.4

Rewrite the program of Example 10.3 using an array member to represent the three subjects.

The modified program is shown in Fig.10.5. You may notice that the use of array name forsubjects has simplified in code.

ARRAYS WI THI N A STRUCTURE

Program

mai n( ){

st r uct mar ks{

i nt sub[ 3] ;i nt t ot al ;

};

Page 85: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 85/120

st r uct marks st udent [ 3] ={45, 67, 81, 0, 75, 53, 69, 0, 57, 36, 71, 0};

st r uct mar ks t ot al ;i nt i , j ;

f or ( i = 0; i <= 2; i ++){

f or ( j = 0; j <= 2; j ++){

s tudent [ i ] . t ot al += s tudent [ i ] . sub[ j ] ;t ot al . sub[ j ] += s tudent [ i ] . sub[ j ] ;

}t ot al . t ot al += s tudent [ i ] . t ot al ;

}pr i nt f ( " STUDENT TOTAL\ n\ n" ) ;f or ( i = 0; i <= 2; i ++)

pr i nt f ( "St udent [ %d] %d\ n", i +1, s t udent [ i ] . t ot al ) ;

pr i nt f ( " \ nSUBJ ECT TOTAL\ n\ n" ) ;f or ( j = 0; j <= 2; j ++)

pr i nt f ( "Subj ect- %d %d\ n", j +1, t ot al . sub[ j ] ) ;

pr i nt f ( " \ nGr and Tot al = %d\ n", t ot al . t ot al ) ;

}

Output

STUDENT TOTALSt udent [ 1] 193St udent [ 2] 197St udent [ 3] 164

SUBJ ECT TOTALSubj ect - 1 177Subj ect - 2 156Subj ect - 3 221

Gr and Tot al = 554

Fig.10.5 Use of subscripted members in structures

Example 10.5

Write a simple program to illustrate the method of sending an entire structure as a parameter to a function.

A program to update an item is shown in Fig.10.6. The function update receives a copy of thestructure variable item as one of its parameters. Note that both the function update and the

Page 86: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 86/120

formal parameter product are declared as type struct stores. It is done so because the functionuses the parameter product to receive the structure variable item and also to return the updatedvalues of item .

The function mul is of type float because it returns the product of price and quantity. However,the parameter stock, which receives the structure variable item is declared as type structstores.

The entire structure returned by update can be copied into a structure of identical type. Thestatement

item = update(item,p_increment,q_increment);

replaces the old values of item by the new ones.STRUCTURES AS FUNCTI ON PARAMETERS

Program

/ * Passi ng a copy of t he ent i r e st r uct ur e */

s t ruct s tores{

char name[ 20] ;f l oat pr i ce;i nt quant i t y;

};s t r uct s t or es updat e ( s t r uct s t or es pr oduct , f l oat p, i nt q) ;f l oat mul ( s t r uct s t or es s tock) ;

mai n( ){

f l oat p_i ncr ement , val ue;i nt q_i ncr ement ;

st r uct st or es i t em = {" XYZ", 25. 75, 12};pr i nt f ( " \ nI nput i ncrement val ues: ") ;pr i nt f ( " pr i ce i ncr ement and quant i t y i ncr ement \ n") ;scanf ( " %f %d" , &p_i ncr ement , &q_i ncr ement ) ;

/ * - - - - - - - - - - - - - - - - - - - - - - - - - - - - * /i t em = updat e( i t em, p_i ncr ement , q_i ncr ement ) ;

/ * - - - - - - - - - - - - - - - - - - - - - - - - - - - - * /pr i nt f ( "Updat ed val ues of i t em\ n\ n") ;pr i nt f ( " Name : %s\ n" , i t em. name) ;pr i nt f ( "Pr i ce : %f \ n" , i t em. pr i ce) ;pr i nt f ( "Quant i t y : %d\ n", i t em. quant i t y) ;

/ * - - - - - - - - - - - - - - - - - - - - - - - - - - - - * /val ue = mul ( i t em) ;

/ * - - - - - - - - - - - - - - - - - - - - - - - - - - - - * /pr i nt f ( " \ nVal ue of t he i t em = %f \ n", val ue) ;

}

st r uct s t or es updat e( s t r uct s t or es pr oduct , f l oat p, i nt q){

Page 87: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 87/120

pr oduct . pr i ce += p;pr oduct . quant i t y += q;r et ur n( pr oduct) ;

}f l oat mul ( s t r uct s t or es s t ock){

r et ur n( st ock. pr i ce * s t ock. quant i t y) ;}

Output

I nput i ncr ement val ues: pr i ce i ncr ement and quant i t y i ncr ement10 12Updat ed val ues of i t em

Name : XYZPr i ce : 35. 750000Quant i t y : 24

Val ue of t he i t em = 858. 000000

Fig.10.6 Using structure as a function parameter

Page 88: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 88/120

Example 11.1

Write a program to print the address of a variable along with its value.

The program shown in Fig.11.4, declares and initializes four variables and then prints out these

values with their respective storage locations. Notice that we have used %u format for printingaddress values. Memory addresses are unsigned integers.

ACCESSI NG ADDRESSES OF VARI ABLESProgram

mai n( ){

char a;i nt x;f l oat p, q;

a = ' A' ;

x = 125;p = 10. 25, q = 18. 76;

pr i nt f ( "%c i s st or ed at addr %u. \ n", a, &a) ;pr i nt f ( "%d i s st or ed at addr %u. \ n", x, &x) ;pr i nt f ( "%f i s st or ed at addr %u. \ n", p, &p) ;pr i nt f ( "%f i s st or ed at addr %u. \ n", q, &q) ;

}

Output

A i s st or ed at addr 4436.125 i s s t or ed at addr 4434.10. 250000 i s st or ed at addr 4442.18. 760000 i s st or ed at addr 4438.

Fig.11.4 Accessing the address of a variable

Example 11.2Write a program to illustrate the use of indirection operator '*' to access the value pointed toby a printer.

The program and output are shown in Fig.11.5. The program clearly shows how we can accessthe value of a variable using a pointer. You may notice that the value of the pointer pt r is 4104and the value it points to is 10. Further, you may also note the following equivalences:

x = *(&x) = *ptr = y&x = &*ptr

ACCESSI NG VARI ABLES USI NG POI NTERS

Page 89: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 89/120

Program

mai n( ){

i nt x, y;i nt * pt r ;

x = 10;pt r = &x;y = *pt r ;

pr i nt f ( "Val ue of x i s %d\ n\ n", x) ;pr i nt f ( "%d i s st or ed at addr %u\ n" , x, &x) ;pr i nt f ( "%d i s st or ed at addr %u\ n" , *&x, &x);pr i nt f ( "%d i s s t or ed at addr %u\ n", *pt r , pt r ) ;pr i nt f ( "%d i s st or ed at addr %u\ n", y, &*pt r ) ;pr i nt f ( "%d i s st or ed at addr %u\ n", pt r , &pt r ) ;pr i nt f ( " %d i s st or ed at addr %u\ n" , y, &y) ;

*pt r = 25;

pr i nt f ( " \ nNow x = %d\ n" , x) ;}

Output

Val ue of x i s 10

10 i s st or ed at addr 410410 i s st or ed at addr 410410 i s st or ed at addr 410410 i s st or ed at addr 41044104 i s st or ed at addr 410610 i s st or ed at addr 4108

Now x = 25

Fig.11.5 Accessing a variable through its pointer

Example 11.3

Write a program to illustrate the use of pointers in arithmetic operations.

The program in Fig.11.7 shows how the pointer variables can be directly used inexpressions. It also illustrates the order of evaluation of expressions. For example, theexpression

4* - *p2 / *p1 + 10

is evaluated as follows:

((4 * (-(*p2))) / (*p1)) + 10

Page 90: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 90/120

When *p1 = 12 and *p2 = 4, this expression evaluates to 9. Remember, since all thevariables are of type int, the entire evaluation is carried out using the integer arithmetic.

I LLUSTRATI ON OF POI NTER EXPRESSI ONS

Program

mai n( ){

i nt a, b, *p1, *p2, x, y, z ;

a = 12;b = 4;p1 = &a;p2 = &b;

x = *p1 * *p2 - 6;y = 4* - *p2 / * p1 + 10;

pr i nt f ( "Addr ess of a = %u\ n" , p1) ;pr i nt f ( "Addr ess of b = %u\ n" , p2) ;pr i nt f ( " \ n" ) ;pr i nt f ( " a = %d, b = %d\ n" , a, b) ;pr i nt f ( " x = %d, y = %d\ n" , x, y) ;

*p2 = *p2 + 3;*p1 = *p2 - 5;z = *p1 * *p2 - 6;

pr i nt f ( " \ na = %d, b = %d, " , a, b) ;pr i nt f ( " z = %d\ n", z) ;

}

Output

Addr ess of a = 4020Addr ess of b = 4016

a = 12, b = 4x = 42, y = 9a = 2, b = 7, z = 8

Fig.11.7 Evaluation of pointer expressions

Example 11.4

Write a program using pointers to compute the sum of all elements stored in an array.

The program shown in Fig.11.8 illustrates how a pointer can be used to traverse an arrayelement. Since incrementing an array pointer causes it to point to the next element, we need onlyto add one to p each time we go through the loop.

POI NTERS I N ONE- DI MENSI ONAL ARRAY

Page 91: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 91/120

Program

mai n( ){

i nt *p, sum, i ;i nt x[ 5] = {5, 9, 6, 3, 7};

i = 0;p = x; / * i ni t i al i z i ng wi t h base addr ess of x */

pr i nt f ( "El ement Val ue Addr ess\ n\ n") ;whi l e( i < 5){

pr i nt f ( " x[ %d] %d %u\ n", i , *p, p) ;sum = sum + *p ; / * accessi ng ar r ay el ement */i ++, p++; / * i ncr ement i ng poi nt er */

}pr i nt f ( "\ n Sum = %d\ n", sum) ;pr i nt f ( "\ n &x[ 0] = %u\ n", &x[ 0] ) ;pr i nt f ( "\ n p = %u\ n", p) ;

}

OutputEl ement Val ue Addr ess

x[ 0] 5 166x[ 1] 9 168x[ 2] 6 170x[ 3] 3 172x[ 4] 7 174

Sum = 55&x[ 0] = 166

p = 176

Fig.11.8 Accessing array elements using the pointer

Example 11.5

Write a program using pointers to determine the length of a character string.

A program to count the length of a string is shown in Fig.11.10. The statement

char *cptr = name;

declares cptr as a pointer to a character and assigns the address of the first character of name as the initial value. Since a string is always terminated by the null character, the statement

whi le(*cpt r != '\0')

is true until the end of the string is reached.

When the while loop is terminated, the pointer cptr holds the address of the null character.Therefore, the statement

length = cptr - name;

Page 92: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 92/120

gives the length of the string name.

D E L H I \0

name cptr

(5 4) (5 9)The output also shows the address location of each character. Note that each characteroccupies one memory cell (byte).

POI NTERS AND CHARACTER STRI NGS

Program

mai n( ){

char *name;i nt l engt h;char *cpt r = name;name = " DELHI " ;pr i nt f ( “%s\ n”, name) ;

whi l e( *cpt r ! = ' \ 0' ){

pr i nt f ( "%c i s st or ed at addr ess %u\ n", *cpt r , cpt r ) ;cpt r ++;

}l engt h = cpt r - name;pr i nt f ( "\ nLengt h of t he st r i ng = %d\ n", l engt h) ;

}

Output

DELHID i s st or ed at addr ess 54E i s st or ed at addr ess 55L i s st or ed at addr ess 56H i s st or ed at addr ess 57I i s st or ed at addr ess 58

Lengt h of t he st r i ng = 5

Fig.11.10 String handling by pointers

Example 11.6

Write a function using pointers to exchange the values stored in two locations in the memory.

Page 93: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 93/120

The program in Fig.11.11 shows how the contents of two locations can be exchanged using theiraddress locations. The function exchange() receives the addresses of the variables x and y andexchanges their contents.

Page 94: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 94/120

POI NTERS AS FUNCTI ON PARAMETERS

Program

voi d exchange ( i nt * , i nt *) ; / * pr ot ot ype */mai n( ){

i nt x, y;x = 100;y = 200;pr i nt f ( " Bef ore exchange : x = %d y = %d\ n\ n" , x, y) ;exchange( &x, &y) ; / * cal l */pr i nt f ( " Af t er exchange : x = %d y = %d\ n\ n" , x, y) ;

}exchange ( i nt *a, i nt *b){

i nt t ;

t = *a; / * Assi gn t he val ue at addr ess a t o t */*a = *b; / * put b i nt o a */*b = t ; / * put t i nt o b */

}

Output

Bef or e exchange : x = 100 y = 200

Af t er exchange : x = 200 y = 100

Fig.11.11 Passing of pointers as function parameters

Example 11.7

Write a program that uses a function pointer as a function argument.

A program to print the function values over a given range of values is shown in Fig.11.12. Theprinting is done by the function table by evaluating the function passed to it by the main.

With table, we declare the parameter f as a pointer to a function as follows:

double (*f)();

The value returned by the function is of type double. When table is called in the statement

table (y, 0.0, 2, 0.5);

we pass a pointer to the function y as the first parameter of table . Note that y is not followed by aparameter list.

During the execution of table, the statement

value = (*f)(a);

Page 95: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 95/120

calls the function y which is pointed to by f, passing it the parameter a. Thus the function y isevaluated over the range 0.0 to 2.0 at the intervals of 0.5.

Similarly, the call

tabl e (cos , 0.0, PI, 0.5);

passes a pointer to co s as its first parameter and therefore, the function table evaluates thevalue of co s over the range 0.0 to PI at the intervals of 0.5.

I LLUSTRATI ON OF POI NTERS TO FUNCTI ONS

Program

#i ncl ude <mat h. h>#def i ne PI 3. 1415926doubl e y( doubl e) ;doubl e cos( doubl e) ;doubl e t abl e ( doubl e( *f ) ( ) , doubl e, doubl e, doubl e) ;

mai n( ){ pr i nt f ( "Tabl e of y( x) = 2*x*x- x+1\ n\ n") ;

t abl e( y, 0. 0, 2. 0, 0. 5) ;

pr i nt f ( " \ nTabl e of cos (x) \ n\ n" ) ;t abl e( cos , 0. 0, PI , 0. 5) ;

}doubl e t abl e( doubl e( *f ) ( ) , doubl e mi n, doubl e max, doubl e st ep)

{ doubl e a, val ue; f or ( a = mi n; a <= max; a += st ep){

val ue = ( *f ) ( a) ;pr i nt f ( "%5. 2f %10. 4f \ n", a, val ue) ;

}}doubl e y( doubl e x){ r et ur n( 2*x*x- x+1) ;

}

Output Tabl e of y( x) = 2*x*x- x+1

0. 00 1. 00000. 50 1. 00001. 00 2. 00001. 50 4. 00002. 00 7. 0000

Tabl e of cos( x)0. 00 1. 00000. 50 0. 87761. 00 0. 5403

Page 96: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 96/120

Page 97: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 97/120

Washi ng machi ne 5 7500. 00El ect r i c_i r on 12 350. 00

Two_i n_one 7 1250. 00

Fig.11.13 Pointer to structure variables

Page 98: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 98/120

Example 12.1

Write a program to read data from the keyboard, write it to a file called INPUT, again read thesame data from the INPUT file, and display it on the screen.

A program and the related input and output data are shown in Fig.12.1. We enter the input datavia the keyboard and the program writes it, character by character, to the file INPUT . The end ofthe data is indicated by entering an EOF character, which is control-Z in the reference system.(This may be control-D in other systems). The file INPUT is closed at this signal.

Page 99: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 99/120

WRI TI NG TO AND READI NG FROM A FI LE

Program

#i ncl ude <st di o. h>

mai n( ){

FI LE *f 1;char c;

pr i nt f ( "Dat a I nput \ n\ n") ;/ * Open t he f i l e I NPUT */f 1 = f open( " I NPUT" , " w" ) ;

/ * Get a char act er f r om keyboar d */whi l e( ( c=get char ( ) ) ! = EOF)

/ * Wr i t e a char act er t o I NPUT */put c( c, f 1) ;

/ * Cl ose t he f i l e I NPUT */f cl os e( f 1) ;

pr i nt f ( " \ nDat a Out put \ n\ n") ;

/ * Reopen t he f i l e I NPUT */f 1 = f open( "I NPUT", "r ") ;

/ * Read a char act er f r om I NPUT*/whi l e( ( c=get c( f 1) ) ! = EOF)

/ * Di spl ay a char act er on scr een */pr i nt f ( "%c" , c) ;

/ * Cl ose t he f i l e I NPUT */f cl os e( f 1) ;

}

Output

Dat a I nput

Thi s i s a pr ogr am t o t est t he f i l e handl i ngf eat ures on t hi s s yst emZ

Dat a Out put Thi s i s a pr ogr am t o t est t he f i l e handl i ngf eat ur es on t hi s syst em

Fig.12.1 Character oriented read/write operations on a file

Page 100: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 100/120

Example 12.2

A file named DATA contains a series of integer numbers. Code a program to read thesenumbers and then write all 'odd' numbers to a file to be called ODD and all `even' numbers toa file to be called EVEN.

The program is shown in Fig.12.2. It uses three files simultaneously and therefore we need to

define three-file pointers f1, f2 and f3.

First, the file DATA containing integer values is created. The integer values are read from theterminal and are written to the file DATA with the help of the statement

putw(number, f1);

Notice that when we type -1, the reading is terminated and the file is closed. The next step is toopen all the three files, DATA for reading, ODD and EVEN for writing. The contents of DATA fileare read, integer by integer, by the function getw(f1) and written to ODD or EVEN file after anappropriate test. Note that the statement

(number = getw(f1)) != EOF

reads a value, assigns the same to number , and then tests for the end-of-file mark.

Finally, the program displays the contents of ODD and EVEN files. It is important to note that thefiles ODD and EVEN opened for writing are closed before they are reopened for reading.

HANDLI NG OF I NTEGER DATA FI LES

Program

#i ncl ude <st di o. h>mai n( ){

FI LE * f 1, * f 2, * f 3;i nt number , i ;

pr i nt f ( "Cont ent s of DATA f i l e\ n\ n") ;f 1 = f open( " DATA" , " w" ) ; / * Cr eat e DATA f i l e */f or ( i = 1; i <= 30; i ++){

scanf ( " %d" , &number ) ;i f ( number == - 1) br eak;put w( number , f 1) ;

}f cl os e( f 1) ;

f 1 = f open( " DATA" , " r " ) ;f 2 = f open( " ODD" , " w" ) ;f 3 = f open( " EVEN" , " w" ) ;

/ * Read f r om DATA f i l e */whi l e( ( number = get w( f 1) ) ! = EOF){

i f ( number %2 == 0)

Page 101: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 101/120

put w( number , f 3) ; / * Wr i t e t o EVEN f i l e */el se

put w( number , f 2) ; / * Wr i t e t o ODD f i l e */}f cl os e( f 1) ;f cl os e( f 2) ;f cl os e( f 3) ;

f 2 = f open( " ODD" , " r " ) ;f 3 = f open( " EVEN" , " r " ) ;pr i nt f ( " \ n\ nCont ent s of ODD f i l e\ n\ n") ;

whi l e( ( number = get w( f 2) ) ! = EOF)pr i nt f ( " %4d" , number ) ;

pr i nt f ( " \ n\ nCont ent s of EVEN f i l e\ n\ n") ;

whi l e( ( number = get w( f 3) ) ! = EOF)pr i nt f ( " %4d" , number ) ;

f cl os e( f 2) ;f cl os e( f 3) ;

}

Output

Cont ent s of DATA f i l e111 222 333 444 555 666 777 888 999 000 121 232 343 454 565 - 1

Cont ent s of ODD f i l e111 333 555 777 999 121 343 565

Cont ent s of EVEN f i l e222 444 666 888 0 232 454

_____________________________________________________________________Fig.12.2 Operations on integer data

Example 12.3

Write a program to open a file named INVENTORY and store in it the following data:

Item name Number Price Quantity

AAA-1 111 17.50 115BBB-2 125 36.00 75C-3 247 31.75 104

Extend the program to read this data from the file INVENTORY and display the inventory tablewith the value of each item.

Page 102: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 102/120

The program is given in Fig.12.3. The filename INVENTORY is supplied through the keyboard.Data is read using the function fscanf from the file stdin, which refers to the terminal and it isthen written to the file that is being pointed to by the file pointer fp. Remember that the filepointer fp points to the file INVENTORY.

After closing the file INVENTORY, it is again reopened for reading. The data from the file, alongwith the item values are written to the file stdout, which refers to the screen. While reading from afile, care should be taken to use the same format specifications with which the contents havebeen written to the file.…é

HANDLI NG OF FI LES WI TH MI XED DATA TYPES(fscanf and fprinf)

Program

#i ncl ude <st di o. h>

mai n( ){

FI LE *f p;i nt number , quant i t y, i ;f l oat pr i ce, val ue;char i t em[ 10] , f i l ename[ 10] ;

pr i nt f ( " I nput f i l e name\ n") ;scanf ( "%s", f i l ename) ;

f p = f open( f i l ename, " w" ) ;

pr i nt f ( " I nput i nvent or y dat a\ n\ n") ;pr i nt f ( " I t em name Number Pr i ce Quant i t y\ n" ) ;f or ( i = 1; i <= 3; i ++){

f scanf ( st di n, " %s %d %f %d" ,i t em, &number , &pr i ce, &quant i t y) ;f pr i nt f ( f p, " %s %d %. 2f %d" ,

i t em, number , pr i ce, quant i t y) ;}f cl os e( f p) ;f pr i nt f ( s t dout , " \ n\ n" ) ;

f p = f open( f i l ename, "r ") ;

pr i nt f ( " I t em name Number Pr i ce Quant i t y Val ue\ n" ) ;f or ( i = 1; i <= 3; i ++){

f scanf ( f p, " %s %d %f d" , i t em, &number , &pr i ce, &quant i t y) ;val ue = pr i ce * quant i t y;f pr i nt f ( st dout , " %- 8s %7d %8. 2f %8d %11. 2f \ n" ,

i t em, number , pr i ce, quant i t y, val ue) ;}f cl os e( f p) ;

}

Page 103: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 103/120

Page 104: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 104/120

f or ( i = 10; i <= 100; i += 10)put w( i , f p1) ;

f cl ose( f p1) ;

pr i nt f ( " \ nI nput f i l ename\ n") ;

open_f i l e:scanf ( "%s", f i l ename) ;

i f ( ( f p2 = f open( f i l ename, " r " ) ) == NULL){

pr i nt f ( "Cannot open t he f i l e. \ n" ) ;pr i nt f ( "Type f i l ename agai n. \ n\ n") ;got o open_f i l e;

}

el se

f or ( i = 1; i <= 20; i ++){ number = get w( f p2) ;

i f ( f eof ( f p2) ){

pr i nt f ( " \ nRan out of dat a. \ n" ) ;br eak;

}el se

pr i nt f ( " %d\ n" , number ) ;}

f cl ose( f p2) ;}

Output

I nput f i l ename TETSCannot open t he f i l e.

Type f i l ename agai n.

TEST1020304050

Page 105: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 105/120

60708090100

Ran out of dat a.

Fig.12.4 Illustration of error handling

Example 12.5

Write a program that uses the functions ftell and fseek.

A program employing ftell and fseek functions is shown in Fig.12.5. We have created a file RANDOM with the following contents:

Position ----> 0 1 2 . . . . . . . . . . . 25

Characterstored ----> A B C . . . . . . . . . . . .Z

We are reading the file twice. First, we are reading the content of every fifth position and printingits value along with its position on the screen. The second time, we are reading the contents ofthe file from the end and printing the same on the screen.

During the first reading, the file pointer crosses the end-of-file mark when the parameter n offsee(fp,n,0) becomes 30. Therefore, after printing the content of position 30, the loop isterminated.

For reading the file from the end, we use the statement

fseek(fp,-1L,2);

to position the file pointer to the last character. Since every read causes the position to moveforward by one position, we have to move it back by two positions to read the next character.This is achieved by the function

fseek(fp, -2L, 1);

in the while statement. This statement also tests whether the file pointer has crossed the fileboundary or not. The loop is terminated as soon as it crosses it.

I LLUSTRATI ON OF f seek & f t el l FUNCTI ONS

Program

#i ncl ude <st di o. h>mai n( ){

FI LE *f p;l ong n;char c;

Page 106: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 106/120

f p = f open( " RANDOM" , " w" ) ;

whi l e( ( c = get char ( ) ) ! = EOF)put c( c, f p) ;

pr i nt f ( "No. of char acters ent er ed = %l d\ n", f t el l ( f p) ) ;f cl os e( f p) ;f p = f open( " RANDOM" , " r " ) ;n = 0L;

whi l e( f eof ( f p) == 0){

f seek( f p, n, 0) ; / * Posi t i on t o ( n+1) t h char acter */pr i nt f ( "Pos i t i on of %c i s %l d\ n" , get c( f p) , f t el l ( f p) ) ;n = n+5L;

}put char ( ' \ n' ) ;

f seek( f p, - 1L, 2) ; / * Pos i t i on t o t he l as t char ac ter * /do{

put char ( get c(f p) ) ;}whi l e( ! f s eek( f p, - 2L, 1) ) ;f cl os e( f p) ;

}

Output

ABCDEFGHI J KLMNOPQRSTUVWXYZ ZNo. of char act er s ent er ed = 26Posi t i on of A i s 0Pos i t i on of F i s 5Posi t i on of K i s 10Posi t i on of P i s 15Posi t i on of U i s 20Posi t i on of Z i s 25Posi t i on of i s 30

ZYXWVUTSRQPONMLKJ I HGFEDCBA

Fig.12.5 Illustration of fseek and ftell functions

Example 12.6

Write a program to append additional items to the file INVENTORY and print the total contentsof the file.

The program is shown in Fig.12.6. It uses a structure definition to describe each item and afunction append() to add an item to the file.

Page 107: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 107/120

On execution, the program requests for the filename to which data is to be appended. Afterappending the items, the position of the last character in the file is assigned to n and then the fileis closed.

The file is reopened for reading and its contents are displayed. Note that reading and displayingare done under the control of a while loop. The loop tests the current file position against n andis terminated when they become equal.

APPENDI NG I TEMS TO AN EXI STI NG FI LE

Program

#i ncl ude <st di o. h>

st r uct i nvent _r ecor d{

char name[ 10] ;i nt number ;f l oat pr i ce;i nt quant i t y;

};

mai n( ){

st r uct i nvent _r ecor d i t em;char f i l ename[ 10] ;i nt r esponse;FI LE *f p;l ong n;

voi d append ( st r uct i nvent _r ecor d 8x, f i l e *y) ;

pr i nt f ( "Type f i l ename: ") ;

scanf ( "%s", f i l ename) ;

f p = f open( f i l ename, " a+" ) ;do{

append( &i t em, f p) ;pr i nt f ( " \ nI t em %s appended. \ n", i t em. name) ;pr i nt f ( " \ nDo you want t o add anot her i t em\

( 1 f or YES / 0 f or NO) ?") ;scanf ( " %d" , &r esponse) ;

} whi l e ( r esponse == 1) ;

n = f t el l ( f p) ; / * Pos i t i on of l as t char act er * /f cl os e( f p) ;

f p = f open( f i l ename, "r ") ;

Page 108: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 108/120

whi l e( f t el l ( f p) < n){

f scanf ( f p, " %s %d %f %d",i t em. name, &i t em. number , &i t em. pr i ce, &i t em. quant i t y) ;f pr i nt f ( st dout , " %- 8s %7d %8. 2f %8d\ n" ,i t em. name, i t em. number , i t em. pr i ce, i t em. quant i t y) ;

}f cl os e( f p) ;

}voi d append( st r uct i nvent _r ecor d *pr oduct , Fi l e *pt r ){

pr i nt f ( " I t em name: " ) ;scanf ( " %s" , pr oduct - >name) ;

pr i nt f ( " I t em number : " ) ;scanf ( " %d" , &pr oduct - >number ) ;

pr i nt f ( " I t em pr i ce: " ) ;scanf ( " %f " , &pr oduct - >pr i ce) ;

pr i nt f ( " Quant i t y: " ) ;scanf ( " %d" , &pr oduct - >quant i t y) ;

f pr i nt f ( pt r , " %s %d %. 2f %d" ,pr oduct - >name,product - >number ,pr oduct - >pr i ce,pr oduct - >quant i t y) ;

}

Output

Type f i l ename: I NVENTORYI t em name: XXXI t em number : 444I t em pr i ce: 40. 50Quant i t y: 34

I t em XXX appended.Do you want t o add anot her i t em( 1 f or YES / 0 f or NO) ?1I t em name: YYYI t em number : 555I t em pr i ce: 50. 50Quant i t y: 45I t em YYY appended.Do you want t o add anot her i t em( 1 f or YES / 0 f or NO) ?0AAA- 1 111 17. 50 115BBB- 2 125 36. 00 75C- 3 247 31. 75 104XXX 444 40. 50 34

YYY 555 50. 50 45

Page 109: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 109/120

Fig.12.6 Adding items to an existing file

Example 12.7

Write a program that will receive a filename and a line of text as command linearguments and write the text to the file.

Figure 12.7 shows the use of command line arguments. The command line is

F12_ 7 TEXT AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG

Each word in the command line is an argument to the main and therefore the total number ofarguments is 9.

The argument vector argv[1] points to the string TEXT and therefore the statement

fp = fopen(argv[1], "w");

opens a file with the name TEXT. The for loop that follows immediately writes the remaining 7arguments to the file TEXT.

COMMAND LI NE ARGUMENTS

Program

#i ncl ude <st di o. h>

mai n( ar gc, ar gv)i nt ar gc; / * ar gument count */char *ar gv[ ] ; / * l i s t of ar gument s */{

FI LE *f p;i nt i ;char word[ 15] ;

f p = f open( ar gv[1] , "w" ) ; / * open f i l e wi t h name ar gv[1] */pr i nt f ( " \ nNo. of argument s i n Command l i ne = %d\ n\ n" , argc) ;f or ( i = 2; i < ar gc; i ++)

f pr i nt f ( f p, " %s " , argv[ i ] ) ; / * wr i t e t o f i l e argv[ 1] * /f cl os e( f p) ;

/ * Wr i t i ng cont ent of t he f i l e t o scr een */

pr i nt f ( "Cont ent s of %s f i l e\ n\ n" , ar gv[ 1] ) ;f p = f open( ar gv[ 1] , "r ") ;f or ( i = 2; i < ar gc; i ++){

f scanf ( f p, "%s", wor d) ;pr i nt f ( "%s " , wor d) ;

Page 110: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 110/120

Page 111: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 111/120

Example 13.1Write a program that uses a table of integers whose size will be specified interactively at runtime.

The program is given in Fig.13.2. It tests for availability of memory space of required size. If it is

available, then the required space is allocated and the address of the first byte of the spaceallocated is displayed. The program also illustrates the use of pointer variable for storing andaccessing the table values.

Page 112: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 112/120

USE OF malloc FUNCTI ON

Program

#i ncl ude <st di o. h>#i ncl ude <st dl i b. h>#def i ne NULL 0

mai n( ){

i nt *p, * t abl e;i nt s i ze;

pr i nt f ( “\ nWhat i s the s i ze of t abl e?”);scanf ( “%d”, si ze) ;

pr i nt f ( “ \ n”)

/ *- - - - - - - - - - - - Memor y al l ocat i on - - - - - - - - - - - - - - * /

i f ( ( t abl e = ( i nt * )mal l oc( s i ze * si zeof ( i nt ) ) ) == NULL){pr i nt f ( “No space avai l abl e \ n”) ;exi t ( 1) ;

}pr i nt f ( “\ n Addr ess of t he f i r s t byt e i s %u\ n”, t abl e) ;

/ * Readi ng t abl e val ues*/

pr i nt f ( “ \ nI nput t abl e val ues \ n”) ;

f or ( p=t abl e; p<t abl e + si ze; p++)scanf ( “%d”, p) ;

/ * Pr i nt i ng t abl e val ues i n r ever se or der */f or ( p = t abl e + si ze –1; p >= t abl e; p - - )

pr i nt f ( “%d i s st or ed at addr ess %u \ n”, *p, p) ;

}

Output

What i s t he si ze of t he t abl e? 5Addr ess of t he f i r st byt e i s 2262

I nput t abl e val ues

11 12 13 14 1515 i s s t or ed at addr ess 227014 i s s t or ed at addr ess 226813 i s s t or ed at addr ess 226612 i s s t or ed at addr ess 226411 i s s t or ed at addr ess 2262

Fig.13.2 Memory allocation with malloc

Page 113: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 113/120

Example 13.2

Write a program to store a character string in a block of memory space created by malloc and then modify the same to store a larger string.

The program is shown in Fig. 13.3. The output illustrates that the original buffer size obtained ismodified to contain a larger string. Note that the original contents of the buffer remains sameeven after modification of the original size.

USE OF r eal l oc AND f r ee FUNCTI ONS

Program

#i ncl ude <st di o. h>#i ncl ude<st dl i b. h>#def i ne NULL 0

mai n( ){

char *buf f er ;

/ * Al l ocat i ng memor y */i f ( ( buf f er = ( char *) mal l oc( 10) ) == NULL){

pr i nt f ( “mal l oc f ai l ed. \ n” ) ;exi t ( 1) ;

}

pr i nt f ( “Buf f er of s i ze %d creat ed \ n”, _msi ze( buf f er ) ) ;st r cpy( buf f er , “HYDERABAD”) ;pr i nt f ( “ \ nBuf f er cont ai ns : %s \ n “ , buf f er ) ;

/ * Real l oc t i on * /

i f ( ( buf f er = ( char *) r eal l oc( buf f er , 15) ) == NULL){

pr i nt f ( “Real l ocat i on f ai l ed. \ n” ) ;exi t ( 1) ;

}pr i nt f ( “ \ nBuf f er s i ze modi f i ed. \ n”) ;pr i nt f ( “ \ nBuf f er s t i l l cont ai ns : %s \ n” , buf f er ) ;

st r cpy( buf f er , “SECUNDERBAD”) ;pr i nt f ( “\ nBuf f er now cont ai ns: %s \ n”, buf f er ) ;

/ * Fr eei ng memor y */

f r ee( buf f er ) ;

}

Output

Buf f er of si ze 10 cr eat edBuf f er cont ai ns: HYDERABADBuf f er si ze modi f i edBuf f er st i l l cont ai ns: HYDERABADBuf f er now cont ai ns: SECUNDERABAD

Page 114: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 114/120

Fig . 13.3 Reallocation and release of memory space

Example 13.3

Write a program to create a linear linked list interactively and print out the list and the totalnumber of items in the list.

The program shown in Fig.13.7 first allocates a block of memory dynamically for the first nodeusing the statement

head = (node *)malloc(sizeof(node));

which returns a pointer to a structure of type node that has been type defined earlier. The linkedlist is then created by the function create . The function requests for the number to be placed inthe current node that has been created. If the value assigned to the current node is –999, thennull is assigned to the pointer variable next and the list ends. Otherwise, memory space isallocated to the next node using again the malloc function and the next value is placed into it.Not that the function create calls itself recursively and the process will continue until we enter thenumber –999.

The items stored in the linked list are printed using the function print which accept a pointer tothe current node as an argument. It is a recursive function and stops when it receives a NULLpointer. Printing algorithm is as follows;

1. Start with the first node.

2. While there are valid nodes left to print

a) print the current item and

b) advance to next node

Similarly, the function count counts the number of items in the list recursively and return the totalnumber of items to the main function. Note that the counting does not include the item –999(contained in the dummy node).

CREATI NG A LI NEAR LI NKED LI ST

Program

#i ncl ude<st di o. h>#i ncl ude<st dl i b. h>#def i ne NULL 0

s t r uct l i nked_ l i s t{

i nt number ;s t r uct l i nked_ l i s t *next ;

};t ypedef st r uct l i nked_l i st node; / * node t ype def i ned */

mai n( )

Page 115: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 115/120

{node *head;voi d cr eat e( node *p) ;i nt count ( node *p) ;voi d pr i nt ( node *p) ;head = ( node *) mal l oc( si zeof ( node) ) ;cr eat e( head) ;pr i nt f ( “ \ n”) ;pr i nt f ( head) ;pr i nt f ( “ \ n”) ;pr i nt f ( “\ nNumber of i t ems = %d \ n”, count ( head) ) ;

}voi d creat e( node *l i s t ){

pr i nt f ( “I nput a number \ n”) ;pr i nt f ( “( t ype –999 at end) : ”) ;scanf ( “%d”, &l i st - > number ) ; / * cr eat e cur r ent node */

i f ( l i st - >number == - 999){l i st - >next = NULL;

}el se / *cr eat e next node */{

l i st - >next = ( node *) mal l oc( si zeof ( node) ) ;cr eat e( l i s t - >next ) ;

}r et ur n;

}

voi d pr i nt ( node * l i s t )

{ i f ( l i st - >next ! = NULL){

pr i nt f ( “%d- - >”, l i s t - >number ) ; / * pr i nt cur r ent i t em */

i f ( l i st - >next - >next == NULL)pr i nt f ( “%d”, l i st - >next- >number ) ;

pr i nt f ( l i s t - >next ) ; / * move t o next i t em */}r et ur n;

}

i nt count ( node *l i s t ){

i f ( l i st - >next == NULL)r et ur n ( 0) ;

el ser et ur n( 1+ count ( l i s t - >next ) ) ;

}

Page 116: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 116/120

Page 117: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 117/120

Output

I nput a number( t ype –999 t o end) ; 60

I nput a number

( t ype –999 t o end) ; 20I nput a number( t ype –999 t o end) ; 10I nput a number( t ype –999 t o end) ; 40

I nput a number( t ype –999 t o end) ; 30

I nput a number( t ype –999 t o end) ; 50

I nput a number( t ype –999 t o end) ; - 999

60 - - >20 - - >10 - - >40 - - >30 - - >50 - - > - 999

Number of i t ems = 6

Fig. 13.7 Creating a linear linked list

Example 13.4

Write a function to insert a given item before a specified node known as key node.

The function insert shown in Fig.13.8 requests for the item to be inserted as well as the‘key node”. If the insertion happens to be at the beginning, then memory space is createdfor the new node, the value of new item is assigned to it and the pointer head is assignedto the next member. The pointer new which indicates the beginning of the new node isassigned to head. Note the following statements:

new->number = x;new->next = head;head = new;

FUNCTI ON I NSERT

node *i nser t ( node *head){

node *f i nd( node *p, i nt a) ;node *new; / * poi nt er t o new node */node *n1; / * poi nt er t o node pr ecedi ng key node */i nt key;

Page 118: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 118/120

i nt x; / * new i t em ( number ) t o be i nser t ed */

pr i nt f ( “Val ue of new i t em?”) ;scanf ( “%d”, &x) ;pr i nt f ( “Val ue of key i t em ? ( t ype –999 i f l as t ) “ ) ;scanf ( “%d”, &key) ;

i f ( head- >number == key) / * new node i s f i r st */{

new = ( node *) mal l oc( si ze of ( node) ) ;new - >number = x;new- >next = head;head = new;

}el se / * f i nd key node and i nser t new node */{ / * bef or e t he key node */

n1 = f i nd( head, key) ; / * f i nd key node */

i f ( n1 == NULL)pr i nt f ( “\ n key i s not f ound \ n”) ;el se / * i nser t new node */{

new = ( node *) mal l oc( si zeof ( node) ) ;new- >number = x;new- >next = n1- >next ;n1- >next = new;

}}

r et ur n( head) ;}node *f i nd( node *l i s t s , i nt key){

i f ( l i st - >next - >number == key) / * key f ound */r et ur n( l i st ) ;

el se

i f ( l i st - >next - >next == NULL) / * end */r et ur n( NULL) ;

el sef i nd( l i s t - >next , key) ;

}

Fig. 13.8 A function for inserting an item into a linked list

Example 13.5

Write a function to delete a specified node.

A function to delete a specified node is given in Fig.13.9. The function first checks whether thespecified item belongs to the first node. If yes, then the pointer to the second node is temporarilyassigned the pointer variable p , the memory space occupied by the first node is freed and the

Page 119: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 119/120

location of the second node is assigned to head . Thus, the previous second node becomes thefirst node of the new list.

If the item to be deleted is not the first one, then we use the find function to locate the position of‘key node’ containing the item to be deleted. The pointers are interchanged with the help of atemporary pointer variable making the pointer in the preceding node to point to the node followingthe key node. The memory space of key node that has been deleted if freed. The figure belowshows the relative position of the key node.

key node

n1 n1->next n1->next->nextThe execution of the following code deletes the key node.

p = n1->next->next;free (n1->next);n1->next = p; n1->next

key node

n1

FUNCTI ON DELETE

node *del et e( node *head){

node *f i nd( node *p, i nt a) ;i nt key; / * i t em t o be del et ed * /

node *n1; / * poi nt er t o node pr ecedi ng key node */node *p; / * t empor ar y poi nt er */

pr i nt f ( “\ n What i s t he i t em ( number ) t o be del et ed?”) ;scanf ( “%d”, &key) ;

i f ( head- >number == key) / * f i r st node t o be del et ed) */{

p = head- >next ; / * poi nt er t o 2 nd node i n l i s t * /f r ee( head) ; / * r el ease space of key node */head = p; / * make head t o poi nt t o 1 st node */

}el se{

n1 = f i nd( head, key) ;

i f ( n1 == NULL)pr i nt f ( “\ n key not f ound \ n”) ;

el se / * del et e key node */{

p = n1- >next - >next ; / * poi nt er t o t he nodef ol l owi ng t he keynode */

Page 120: Ansi C Programs

8/13/2019 Ansi C Programs

http://slidepdf.com/reader/full/ansi-c-programs 120/120

f r ee( n1- >next ) ; / * f r ee key node */n1- >next = p; / * est abl i sh l i nk */

}}

r et ur n( head) ;}

/ * USE FUNCTI ON f i nd( ) HERE */

Fig.13.9 A function for deleting an item from linked list