# C program.



Example 7.1
Write a program using a single-subscripted variable to evaluate the following expressions:
10
Total =  x i2
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 of their squares.



PROGRAM SHOWING ONE-DIMENSIONAL ARRAY
Program :
main()
{
int i ;
float x[10], value, total ;

/* . . . . . .READING VALUES INTO ARRAY . . . . . . */

printf("ENTER 10 REAL NUMBERS\n") ;

for( i = 0 ; i < 10 ; i++ )
{
scanf("%f", &value) ;
x[i] = value ;
}
/* . . . . . . .COMPUTATION OF TOTAL . . . . . . .*/

total = 0.0 ;
for( i = 0 ; i < 10 ; i++ )
total = total + x[i] * x[i] ;

/*. . . . PRINTING OF x[i] VALUES AND TOTAL . . . */

printf("\n");
for( i = 0 ; i < 10 ; i++ )
printf("x[%2d] = %5.2f\n", i+1, x[i]) ;

printf("\ntotal = %.2f\n", total) ;
}

Output
ENTER 10 REAL NUMBERS
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10

x[ 1] = 1.10
x[ 2] = 2.20
x[ 3] = 3.30
x[ 4] = 4.40
x[ 5] = 5.50
x[ 6] = 6.60
x[ 7] = 7.70
x[ 8] = 8.80
x[ 9] = 9.90
x[10] = 10.10

Total = 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 37
40 49 16 75 87 91 33 24 58 78 65 56 76 67 45 54 36 63 12 21
73 49 51 19 39 49 68 93 85 59
Write a program to count the number of students belonging to each of following groups of marks: 0-9, 10-19, 20-29,.....,100.

The program coded in Fig.7.2 uses the array group containing 11 elements, one for each range of 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. For example, consider the value 59. The integer division of 59 by 10 yields 5. This is the element into which 59 is counted.

PROGRAM FOR FREQUENCY COUNTING
Program
#define MAXVAL 50
#define COUNTER 11
main()
{
float value[MAXVAL];
int i, low, high;
int group[COUNTER] = {0,0,0,0,0,0,0,0,0,0,0};
/* . . . . . . . .READING AND COUNTING . . . . . .*/
for( i = 0 ; i < MAXVAL ; i++ )
{
/*. . . . . . . .READING OF VALUES . . . . . . . . */
scanf("%f", &value[i]) ;
/*. . . . . .COUNTING FREQUENCY OF GROUPS. . . . . */
++ group[ (int) ( value[i] + 0.5 ) / 10] ;
}
/* . . . .PRINTING OF FREQUENCY TABLE . . . . . . .*/
printf("\n");
printf(" GROUP RANGE FREQUENCY\n\n") ;
for( i = 0 ; i < COUNTER ; i++ )
{
low = i * 10 ;
if(i == 10)
high = 100 ;
else
high = low + 9 ;
printf(" %2d %3d to %3d %d\n",
i+1, low, high, group[i] ) ;
}
}


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



GROUP RANGE FREQUENCY
1 0 to 9 2
2 10 to 19 4
3 20 to 29 4
4 30 to 39 5
5 40 to 49 8
6 50 to 59 8
7 60 to 69 7
8 70 to 79 6
9 80 to 89 4
10 90 to 99 2
11 100 to 100 0
Fig.7.2 Program for frequency counting



Example 7.3
Write a program using a two-dimensional array to compute and print the following information 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.


The program and its output are shown in Fig.7.4. The program uses the variable value in two-dimensions with the index i representing girls and j representing items. The following equations are used in computing the results:

2
(a) Total sales by m th girl =  value [m][j]
(girl_total[m]) j = 0

3
(b) Total value of nth item =  value [i][n]
(item_total[n]) i = 0

3 2
(c) Grand total =   value[i][j]
i = 0 j = 0

3
=  girl_total[i]
i = 0

2
=  item_total[j]
j = 0

PROGRAM SHOWING TWO-DIMENSIONAL ARRAYS
Program:
#define MAXGIRLS 4
#define MAXITEMS 3
main()
{
int value[MAXGIRLS][MAXITEMS];
int girl_total[MAXGIRLS] , item_total[MAXITEMS];
int i, j, grand_total;

/*.......READING OF VALUES AND COMPUTING girl_total ...*/

printf("Input data\n");
printf("Enter values, one at a time, row-wise\n\n");

for( i = 0 ; i < MAXGIRLS ; i++ )
{
girl_total[i] = 0;
for( j = 0 ; j < MAXITEMS ; j++ )
{
scanf("%d", &value[i][j]);
girl_total[i] = girl_total[i] + value[i][j];
}
}
/*.......COMPUTING item_total..........................*/

for( j = 0 ; j < MAXITEMS ; j++ )
{
item_total[j] = 0;
for( i =0 ; i < MAXGIRLS ; i++ )
item_total[j] = item_total[j] + value[i][j];
}


/*.......COMPUTING grand_total.........................*/

grand_total = 0;
for( i =0 ; i < MAXGIRLS ; i++ )
grand_total = grand_total + girl_total[i];

/* .......PRINTING OF RESULTS...........................*/

printf("\n GIRLS TOTALS\n\n");
for( i = 0 ; i < MAXGIRLS ; i++ )
printf("Salesgirl[%d] = %d\n", i+1, girl_total[i] );
printf("\n ITEM TOTALS\n\n");
for( j = 0 ; j < MAXITEMS ; j++ )
printf("Item[%d] = %d\n", j+1 , item_total[j] );
printf("\nGrand Total = %d\n", grand_total);
}

Output

Input data
Enter values, one at a time, row_wise

310 257 365
210 190 325
405 235 240
260 300 380

GIRLS TOTALS

Salesgirl[1] = 950
Salesgirl[2] = 725
Salesgirl[3] = 880
Salesgirl[4] = 940

ITEM TOTALS

Item[1] = 1185
Item[2] = 1000
Item[3] = 1310

Grand Total = 3495


Fig.7.4 Illustration of two-dimensional arrays.

Example 7.4
Write a program to compute and print a multiplication table for numbers 1 to 5 as shown below:
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 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:
product(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+1
column = j+1
PROGRAM TO PRINT MULTIPLICATION TABLE
Program:
#define ROWS 5
#define COLUMNS 5
main()
{ int row, column, product[ROWS][COLUMNS] ;
int i, j ;
printf(" MULTIPLICATION TABLE\n\n") ;
printf(" ") ;
for( j = 1 ; j <= COLUMNS ; j++ )
printf("%4d" , j ) ;
printf("\n") ;
printf("-------------------------\n");
for( i = 0 ; i < ROWS ; i++ )
{ row = i + 1 ;
printf("%2d |", row) ;
for( j = 1 ; j <= COLUMNS ; j++ )
{ column = j ;
product[i][j] = row * column ;
printf("%4d", product[i][j] ) ;
}
printf("\n") ;
}
}

Output

MULTIPLICATION TABLE
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25

Fig.7.5 Program to print multiplication table using two-dimensional array




Example 7.5
A survey to know the popularity of four cars (Ambassador, Fiat, Dolphin and Maruti) was conducted in four cities (Bombay, Calcutta, Delhi and Madras). Each person surveyed was asked to give his city and the type of car he was using. The results, in coded form, are tabulated as follows:

M 1 C 2 B 1 D 3 M 2 B 4
C 1 D 3 M 4 B 2 D 1 C 3
D 4 D 4 M 1 M 1 B 3 B 3
C 1 C 1 C 2 M 4 M 4 C 2
D 1 C 2 B 3 M 1 B 1 C 2
D 3 M 4 C 1 D 2 M 3 B 4
Codes represent the following information:
M - Madras 1 - Ambassador
D – Delhi 2 - Fiat
C – Calcutta 3 - Dolphin
B – Bombay 4 - Maruti
Write a program to produce a table showing popularity of various cars in four cities.

A two-dimensional array frequency is used as an accumulator to store the number of cars used, under various categories in each city. For example, the element frequency [i][j] denotes the number of cars of type j used in city i. The frequency is declared as an array of size 5x5 and all the elements are initialized to zero.

The program shown in fig.7.6 reads the city code and the car code, one set after another, from the terminal. Tabulation ends when the letter X is read in place of a city code.


PROGRAM TO TABULATE SURVEY DATA
Program
main()
{
int i, j, car;
int frequency[5][5] = { {0},{0},{0},{0},{0} };
char city;
printf("For each person, enter the city code \n");
printf("followed by the car code.\n");
printf("Enter the letter X to indicate end.\n");
/*. . . . . . TABULATION BEGINS . . . . . */
for( i = 1 ; i < 100 ; i++ )
{
scanf("%c", &city );
if( city == 'X' )
break;
scanf("%d", &car );

switch(city)
{

case 'B' : frequency[1][car]++;
break;
case 'C' : frequency[2][car]++;
break;
case 'D' : frequency[3][car]++;
break;
case 'M' : frequency[4][car]++;
break;
}
}
/*. . . . .TABULATION COMPLETED AND PRINTING BEGINS. . . .*/
printf("\n\n");
printf(" POPULARITY TABLE\n\n");
printf("-------------------------------------------\n");
printf("City Ambassador Fiat Dolphin Maruti \n");
printf("-------------------------------------------\n");
for( i = 1 ; i <= 4 ; i++ )
{


switch(i)
{
case 1 : printf("Bombay ") ;
break ;
case 2 : printf("Calcutta ") ;
break ;
case 3 : printf("Delhi ") ;
break ;
case 4 : printf("Madras ") ;
break ;
}
for( j = 1 ; j <= 4 ; j++ )
printf("%7d", frequency[i][j] ) ;
printf("\n") ;
}
printf("-------------------------------------------\n");
/*. . . . . . . . . PRINTING ENDS. . . . . . . . . . .*/
}

Output

For each person, enter the city code
followed by the car code.
Enter the letter X to indicate end.

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

POPULARITY TABLE
-------------------------------------------
City Ambassador Fiat Dolphin Maruti
-------------------------------------------
Bombay 2 1 3 2
Calcutta 4 5 1 0
Delhi 2 1 3 2
Madras 4 1 1 4
-------------------------------------------


Fig.7.6 Program to tabulate a survey data

#C program.


Example 6.1
A program to evaluate the equation
y = xn
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 loop control variable, count is initialized outside the loop and incremented inside the loop. When the value of count becomes greater than n, the control exists the loop.

EXAMPLE OF while STATEMENT
Program
main()
{
int count, n;
float x, y;

printf("Enter the values of x and n : ");
scanf("%f %d", &x, &n);
y = 1.0;
count = 1; /* Initialisation */

/* LOOP BEGINs */

while ( count <= n) /* Testing */
{
y = y*x;
count++; /* Incrementing */
}
/* END OF LOOP */
printf("\nx = %f; n = %d; x to power n = %f\n",x,n,y);
}


Output

Enter the values of x and n : 2.5 4
x = 2.500000; n = 4; x to power n = 39.062500

Enter the values of x and n : 0.5 4
x = 0.500000; n = 4; x to power n = 0.062500

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







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 is executed 10 times, each time the outer loop is executed. That is, the inner loop is executed a total of 120 times, each time printing a value in the table.
PRINTING OF MULTIPLICATION TABLE
Program:
#define COLMAX 10
#define ROWMAX 12

main()
{
int row,column, y;

row = 1;
printf(" MULTIPLICATION TABLE \n");
printf("-----------------------------------------\n");
do /*......OUTER LOOP BEGINS........*/
{
column = 1;

do /*.......INNER LOOP BEGINS.......*/
{
y = row * column;
printf("%4d", y);
column = column + 1;
}
while (column <= COLMAX); /*... INNER LOOP ENDS ...*/

printf("\n");
row = row + 1;
}
while (row <= ROWMAX);/*..... OUTER LOOP ENDS .....*/

printf("-----------------------------------------\n");
}

Output
MULTIPLICATION TABLE
-------------------------------------------------------
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
11 22 33 44 55 66 77 88 99 110
12 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 value
p = 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.


Additional Features of for Loop

The for loop in C has several capabilities that are not found in other loop constructs. For example, 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)




USE OF for LOOP
Program:
main()
{
long int p;
int n;
double q;
printf("------------------------------------------\n");
printf(" 2 to power n n 2 to power -n\n");
printf("------------------------------------------\n");
p = 1;
for (n = 0; n < 21 ; ++n) /* LOOP BEGINS */
{
if (n == 0)
p = 1;
else
p = p * 2;
q = 1.0/(double)p ;
printf("%10ld %10d %20.12lf\n", p, n, q);
} /* LOOP ENDS */
printf("------------------------------------------\n");
}

Output -----------------------------------------------
2 to power n n 2 to power -n
-----------------------------------------------
1 0 1.000000000000
2 1 0.500000000000
4 2 0.250000000000
8 3 0.125000000000
16 4 0.062500000000
32 5 0.031250000000
64 6 0.015625000000
128 7 0.007812500000
256 8 0.003906250000
512 9 0.001953125000
1024 10 0.000976562500
2048 11 0.000488281250
4096 12 0.000244140625
8192 13 0.000122070313
16384 14 0.000061035156
32768 15 0.000030517578
65536 16 0.000015258789
131072 17 0.000007629395
262144 18 0.000003814697
524288 19 0.000001907349
1048576 20 0.000000953674
-----------------------------------------------

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

Example 6.4
A class of n students take an annual examination in m subjects. A program to read the marks obtained by each student in various subjects and to compute and print the total marks obtained 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 for controlling the number of subjects. Since both the number of students and the number of subjects are requested by the program, the program may be used for a class of any size and any number 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.

ILLUSTRATION OF NESTED LOOPS
Program

#define FIRST 360
#define SECOND 240
main()
{
int n, m, i, j,
roll_number, marks, total;
printf("Enter number of students and subjects\n");
scanf("%d %d", &n, &m);
printf("\n");
for (i = 1; i <= n ; ++i)
{
printf("Enter roll_number : ");
scanf("%d", &roll_number);
total = 0 ;
printf("\nEnter marks of %d subjects for ROLL NO %d\n",
m,roll_number);
for (j = 1; j <= m; j++)
{
scanf("%d", &marks);
total = total + marks;
}
printf("TOTAL MARKS = %d ", total);
if (total >= FIRST)
printf("( First Division )\n\n");
else if (total >= SECOND)
printf("( Second Division )\n\n");
else
printf("( *** F A I L *** )\n\n");
}
}


Output Enter number of students and subjects
3 6
Enter roll_number : 8701
Enter marks of 6 subjects for ROLL NO 8701
81 75 83 45 61 59
TOTAL MARKS = 404 ( First Division )

Enter roll_number : 8702
Enter marks of 6 subjects for ROLL NO 8702
51 49 55 47 65 41
TOTAL MARKS = 308 ( Second Division )

Enter roll_number : 8704
Enter marks of 6 subjects for ROLL NO 8704
40 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 written to read 1000 values. However, if we want the program to calculate the average of any set of values less than 1000, then we must enter a 'negative' number after the last value in the list, to mark the end of input.

USE OF break IN A PROGRAM
Program
main()
{
int m;
float x, sum, average;

printf("This program computes the average of a
set of numbers\n");
printf("Enter values one after another\n");
printf("Enter a NEGATIVE number at the end.\n\n");
sum = 0;
for (m = 1 ; m < = 1000 ; ++m)
{
scanf("%f", &x);
if (x < 0)
break;
sum += x ;
}

average = sum/(float)(m-1);
printf("\n");
printf("Number of values = %d\n", m-1);
printf("Sum = %f\n", sum);
printf("Average = %f\n", average);
}

Output

This program computes the average of a set of numbers
Enter values one after another
Enter a NEGATIVE number at the end.

21 23 24 22 26 22 -1

Number of values = 6
Sum = 138.000000
Average = 23.000000


Fig.6.8 Use of break in a program



Example 6.6
A program to evaluate the series
1
------ = 1 + x + x2 + x3 + ..... + xn
1-x
for -1 < x < 1 with 0.01 per cent accuracy is given in Fig.6.9. The goto statement is used to exit the loop on achieving the desired accuracy.

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








EXAMPLE OF exit WITH goto STATEMENT
Program
#define LOOP 100
#define ACCURACY 0.0001
main()
{
int n;
float x, term, sum;

printf("Input value of x : ");
scanf("%f", &x);
sum = 0 ;
for (term = 1, n = 1 ; n < = LOOP ; ++n)
{
sum += term ;
if (term < = ACCURACY)
goto output; /* EXIT FROM THE LOOP */
term *= x ;
}
printf("\nFINAL VALUE OF N IS NOT SUFFICIENT\n");
printf("TO ACHIEVE DESIRED ACCURACY\n");
goto end;
output:
printf("\nEXIT FROM LOOP\n");
printf("Sum = %f; No.of terms = %d\n", sum, n);
end:
; /* Null Statement */
}


Output
Input value of x : .21
EXIT FROM LOOP
Sum = 1.265800; No.of terms = 7
Input value of x : .75
EXIT FROM LOOP
Sum = 3.999774; No.of terms = 34
Input value of x : .99
FINAL VALUE OF N IS NOT SUFFICIENT
TO ACHIEVE DESIRED 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 root should be bypassed for such numbers because the square root of a negative number is not defined. The continue statement is used to achieve this. The program also prints a message saying that the number is negative and keeps an account of negative numbers.

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


USE OF continue STATEMENT
Program:
#include

main()
{
int count, negative;
double number, sqroot;

printf("Enter 9999 to STOP\n");
count = 0 ;
negative = 0 ;

while (count < = 100)
{
printf("Enter a number : ");
scanf("%lf", &number);
if (number == 9999)
break; /* EXIT FROM THE LOOP */
if (number < 0)
{
printf("Number is negative\n\n");
negative++ ;
continue; /* SKIP REST OF THE LOOP */
}
sqroot = sqrt(number);
printf("Number = %lf\n Square root = %lf\n\n",
number, sqroot);
count++ ;
}
printf("Number of items done = %d\n", count);
printf("\n\nNegative items = %d\n", negative);
printf("END OF DATA\n");
}







Output

Enter 9999 to STOP
Enter a number : 25.0
Number = 25.000000
Square root = 5.000000

Enter a number : 40.5
Number = 40.500000
Square root = 6.363961

Enter a number : -9
Number is negative

Enter a number : 16
Number = 16.000000
Square root = 4.000000

Enter a number : -14.75
Number is negative

Enter a number : 80
Number = 80.000000
Square root = 8.944272

Enter a number : 9999
Number of items done = 4
Negative items = 2
END OF DATA
_______________________________________________________________

Fig.6.11 Use of continue statement

C program.


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's response 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
#include

main()
{
char answer;

printf("Would you like to know my name?\n");
printf("Type Y for YES and N for NO: ");

answer = getchar(); /* .... Reading a character...*/

if(answer == 'Y' || answer == 'y')
printf("\n\nMy name is BUSY BEE\n");
else
printf("\n\nYou are good for nothing\n");
}


Output

Would you like to know my name?
Type Y for YES and N for NO: Y

My name is BUSY BEE

Would you like to know my name?
Type Y for YES and N for NO: n

You are good for nothing


Fig.4.1 Use of getchar function



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

This program receives a character from the keyboard and tests whether it is a letter or digit and prints out a message accordingly. These tests are done with the help of the following functions:
isalpha(character)
isdigit(character)
For example, isalpha assumes a value non-zero (TRUE) if the argument character contains an alphabet; otherwise it assumes 0 (FALSE). Similar is the case with the function isdigit.
TESTING CHARACTER TYPE
Program:
#include
#include
main()
{
char character;
printf("Press any key\n");
character = getchar();
if (isalpha(character) > 0)
printf("The character is a letter.");
else
if (isdigit (character) > 0)
printf("The character is a digit.");
else
printf("The character is not alphanumeric.");
}

Output

Press any key
h
The character is a letter.

Press any key
5
The character is a digit.

Press any key
*
The character is not alphanumeric.
________________________________________________________________________
Fig.4.2 Program to test the character type



Example 4.3
A program that reads a character from keyboard and then prints it in reverse case is given in Fig.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 is a 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 into an upper case alphabet while the function tolower does the reverse.

WRITING A CHARACTER TO THE SCREEN

Program

#include
#include

main()
{
char alphabet;
printf("Enter an alphabet");
putchar('\n'); /* move to next line */
alphabet = getchar();
if (islower(alphabet))
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
}




Output
Enter an alphabet
a
A
Enter an alphabet
Q
q
Enter an alphabet
z
Z

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 three values 1, 2, and 3 are keyed in. Because of the specification %*d the value 2 has been skipped and 3 is assigned to the variable b. Notice that since no data is available for c, it contains garbage.

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 not contain more digits that the specified size. Otherwise, the extra digits on the right-hand side will be truncated and assigned to the next variable in the list. Thus, the second scanf has truncated the four digit number 6789 and assigned 67 to x and 89 to y. The value 4321 has been assigned to the first variable in the immediately following scanf statement.

READING INTEGER NUMBERS
Program:
main()
{
int a,b,c,x,y,z;
int p,q,r;

printf("Enter three integer numbers\n");
scanf("%d %*d %d",&a,&b,&c);
printf("%d %d %d \n\n",a,b,c);

printf("Enter two 4-digit numbers\n");
scanf("%2d %4d",&x,&y);
printf("%d %d\n\n", x,y);

printf("Enter two integers\n");
scanf("%d %d", &a,&x);
printf("%d %d \n\n",a,x);

printf("Enter a nine digit number\n");
scanf("%3d %4d %3d",&p,&q,&r);
printf("%d %d %d \n\n",p,q,r);

printf("Enter two three digit numbers\n");
scanf("%d %d",&x,&y);
printf("%d %d",x,y);
}

Output
Enter three integer numbers
1 2 3
1 3 -3577
Enter two 4-digit numbers
6789 4321
67 89
Enter two integers
44 66
4321 44
Enter a nine-digit number
123456789
66 1234 567
Enter two three-digit numbers
123 456
89 123


Fig.4.4 Reading integers using scanf



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

READING OF REAL NUMBERS
Program:
main()
{
float x,y;
double p,q;
printf("Values of x and y:");
scanf("%f %e", &x, &y);
printf("\n");
printf("x = %f\ny = %f\n\n", x, y);
printf("Values of p and q:");
scanf("%lf %lf", &p, &q);
printf("\np = %lf\nq = %e",p,q);
printf("\n\np = %.12lf\np = %.12e", p,q);
}

Output

Values of x and y:12.3456 17.5e-2
x = 12.345600
y = 0.175000
Values of p and q:4.142857142857 18.5678901234567890
p = 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. When we 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 is automatically assigned to name3. However, during the second run, the string "New-York" is correctly assigned to name2.








READING STRINGS
Program
main()
{
int no;
char name1[15], name2[15], name3[15];
printf("Enter serial number and name one\n");
scanf("%d %15c", &no, name1);
printf("%d %15s\n\n", no, name1);
printf("Enter serial number and name two\n");
scanf("%d %s", &no, name2);
printf("%d %15s\n\n", no, name2);
printf("Enter serial number and name three\n");
scanf("%d %15s", &no, name3);
printf("%d %15s\n\n", no, name3);
}

Output
Enter serial number and name one
1 123456789012345
1 123456789012345r
Enter serial number and name two
2 New York
2 New
Enter serial number and name three
2 York
Enter serial number and name one
1 123456789012
1 123456789012 r
Enter serial number and name two
2 New-York
2 New-York
Enter serial number and name three
3 London
3 London


Fig. 4.6 Reading of strings



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


ILLUSTRATION OF %[ ] SPECIFICATION
Program-A

main()
{
char address[80];
printf("Enter address\n");
scanf("%[a-z’]", address);
printf("%-80s\n\n", address);
}
Output

Enter address
new delhi 110002
new delhi


ILLUSTRATION OF %[^ ] SPECIFICATION
Program-B
main()
{
char address[80];

printf("Enter address\n");
scanf("%[^\n]", address);
printf("%-80s", address);
}

Output
Enter address
New Delhi 110 002
New Delhi 110 002

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



Example 4.8
The program presented in Fig.4.8 illustrates the testing for correctness of reading of data by scanf function.
The function scanf is expected to read three items of data and therefore, when the values for all the 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 terminated and 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 is assigned 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.

TESTING FOR CORRECTNESS OF INPUT DATA
Program
main()
{
int a;
float b;
char c;
printf("Enter values of a, b and c\n");
if (scanf("%d %f %c", &a, &b, &c) == 3)
printf("a = %d b = %f c = %c\n" , a, b, c);
else
printf("Error in input.\n");
}
Output Enter values of a, b and c
12 3.45 A
a = 12 b = 3.450000 c = A
Enter values of a, b and c
23 78 9
a = 23 b = 78.000000 c = 9
Enter values of a, b and c
8 A 5.25
Error in input.
Enter values of a, b and c
Y 12 67
Error in input.
Enter values of a, b and c
15.75 23 X
a = 15 b = 0.750000 c = 2

Fig.4.8 Detection of errors in scanf input



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



PRINTING OF INTEGER NUMBERS
Program:
main()
{
int m = 12345;
long n = 987654;

printf("%d\n",m);
printf("%10d\n",m);
printf("%010d\n",m);
printf("%-10d\n",m);
printf("%10ld\n",n);
printf("%10ld\n",-n);
}

Output

12345
12345
0000012345
12345
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.

PRINTING OF REAL NUMBERS
Program:
main()
{
float y = 98.7654;
printf("%7.4f\n", y);
printf("%f\n", y);
printf("%7.2f\n", y);
printf("%-7.2f\n", y);
printf("%07.2f\n", y);
printf("%*.*f", 7, 2, y);
printf("\n");
printf("%10.2e\n", y);
printf("%12.4e\n", -y);
printf("%-10.2e\n", y);
printf("%e\n", y);
}
Output 98.7654
98.765404
98.77
98.77
0098.77
98.77
9.88e+001
-9.8765e+001
9.88e+001
9.876540e+001

Fig.4.10 Formatted output of real numbers



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




PRINTING OF CHARACTERS AND STRINGS
Program

main()
{
char x = 'A';
static char name[20] = "ANIL KUMAR GUPTA";

printf("OUTPUT OF CHARACTERS\n\n");
printf("%c\n%3c\n%5c\n", x,x,x);
printf("%3c\n%c\n", x,x);
printf("\n");

printf("OUTPUT OF STRINGS\n\n");
printf("%s\n", name);
printf("%20s\n", name);
printf("%20.10s\n", name);
printf("%.5s\n", name);
printf("%-20.10s\n", name);
printf("%5s\n", name);
}

Output

OUTPUT OF CHARACTERS

A
A
A
A
A

OUTPUT OF STRINGS

ANIL KUMAR GUPTA
ANIL KUMAR GUPTA
ANIL KUMAR
ANIL
ANIL KUMAR
ANIL KUMAR GUPTA


Fig.4.11 Printing of characters and strings

#C program.


Example 5.1
The program in Fig.5.3 reads four values a, b, c, and d from the terminal and evaluates the ratio 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 paths function properly. The result of the first run is printed as

Ratio = -3.181818

ILLUSTRATION OF if STATEMENT

Program

main()
{
int a, b, c, d;
float ratio;

printf("Enter four integer values\n");
scanf("%d %d %d %d", &a, &b, &c, &d);

if (c-d != 0) /* Execute statement block */
{
ratio = (float)(a+b)/(float)(c-d);
printf("Ratio = %f\n", ratio);
}
}


Output

Enter four integer values
12 23 34 45
Ratio = -3.181818

Enter four integer values
12 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 height is greater than 170 cm.

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

if (weight < 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 is another if statement. This if statement tests height and if the height is greater than 170, then the count is incremented by 1.


COUNTING WITH if
Program

main()
{
int count, i;
float weight, height;
count = 0;
printf("Enter weight and height for 10 boys\n");

for (i =1; i <= 10; i++)
{
scanf("%f %f", &weight, &height);
if (weight < 50 && height > 170)
count = count + 1;
}
printf("Number of boys with weight < 50 kgs\n");
printf("and height > 170 cm = %d\n", count);
}



Output

Enter weight and height for 10 boys
45 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 with weight < 50 kgs
and height > 170 cm = 3


Fig. 5.4 Use of if for counting




Example 5.3
A program to evaluate the power series
x2 x3 xn
ex = 1 + x + --- + --- + ..... + ---- , 0 < x < 1
2! 3! n!
is given in Fig. 5.6. It uses if......else to test the accuracy.

The power series contains the recurrence relationship of the type


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


T1 = x for n = 1

T0 = 1

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

ex = T0 + T1 + T2 + ...... + Tn = sum


EXPERIMENT WITH if...else STATEMENT
Program

#define ACCURACY 0.0001

main()
{
int n, count;
float x, term, sum;

printf("Enter value of x:");
scanf("%f", &x);

n = term = sum = count = 1;

while (n <= 100)
{
term = term * x/n;
sum = sum + term;
count = count + 1;
if (term < ACCURACY)
n = 999;
else
n = n + 1;
}

printf("Terms = %d Sum = %f\n", count, sum);

}




Output

Enter value of x:0
Terms = 2 Sum = 1.000000

Enter value of x:0.1
Terms = 5 Sum = 1.105171

Enter value of x:0.5
Terms = 7 Sum = 1.648720

Enter value of x:0.75
Terms = 8 Sum = 2.116997

Enter value of x:0.99
Terms = 9 Sum = 2.691232

Enter value of x:1
Terms = 9 Sum = 2.718279


Fig 5.6 Illustration of if...else statement



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


SELECTING THE LARGEST OF THREE VALUES

Program

main()
{
float A, B, C;

printf("Enter three values\n");
scanf("%f %f %f", &A, &B, &C);

printf("\nLargest value is ");

if (A>B)
{
if (A>C)
printf("%f\n", A);
else
printf("%f\n", C);
}
else
{
if (C>B)
printf("%f\n", C);
else
printf("%f\n", B);
}
}

Output

Enter three values
23445 67379 88843

Largest value is 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 unit
201 - 400 Rs. 100 plus Rs.0.65 per unit excess of 200
401 - 600 Rs. 230 plus Rs.0.80 per unit excess of 400
601 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 prints the amount to be paid by the customer.


USE OF else if LADDER
Program
main()
{
int units, custnum;
float charges;

printf("Enter CUSTOMER NO. and UNITS consumed\n");
scanf("%d %d", &custnum, &units);
if (units <= 200)
charges = 0.5 * units;
else if (units <= 400)
charges = 100 + 0.65 * (units - 200); else if (units <= 600)
charges = 230 + 0.8 * (units - 400);
else
charges = 390 + (units - 600);

printf("\n\nCustomer No: %d: Charges = %.2f\n",
custnum, charges);
}
Output

Enter CUSTOMER NO. and UNITS consumed 101 150
Customer No:101 Charges = 75.00

Enter CUSTOMER NO. and UNITS consumed 202 225
Customer No:202 Charges = 116.25

Enter CUSTOMER NO. and UNITS consumed 303 375
Customer No:303 Charges = 213.75

Enter CUSTOMER NO. and UNITS consumed 404 520
Customer No:404 Charges = 326.00

Enter CUSTOMER NO. and UNITS consumed 505 625
Customer No:505 Charges = 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 be sanctioned 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

#define MAXLOAN 50000

main()
{
long int loan1, loan2, loan3, sancloan, sum23;

printf("Enter the values of previous two loans:\n");
scanf(" %ld %ld", &loan1, &loan2);

printf("\nEnter the value of new loan:\n");
scanf(" %ld", &loan3);

sum23 = loan2 + loan3;
sancloan = (loan1>0)? 0 : ((sum23>MAXLOAN)?
MAXLOAN - loan2 : loan3);

printf("\n\n");
printf("Previous loans pending:\n%ld %ld\n",loan1,loan2);
printf("Loan requested = %ld\n", loan3);
printf("Loan sanctioned = %ld\n", sancloan);

}
Output

Enter the values of previous two loans:
0 20000
Enter the value of new loan:
45000
Previous loans pending:
0 20000
Loan requested = 45000
Loan sanctioned = 30000
Enter the values of previous two loans:
1000 15000
Enter the value of new loan:
25000
Previous loans pending:
1000 15000
Loan requested = 25000
Loan sanctioned = 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 count of numbers read. When count is less than or equal to 5, goto read; directs the control to the label read; otherwise, the program prints a message and stops.


USE OF goto STATEMENT
Program
#include
main()
{
double x, y;
int count;

count = 1;

printf("Enter FIVE real values in a LINE \n");
read:
scanf("%lf", &x);
printf("\n");
if (x < 0)
printf("Value - %d is negative\n",count);
else
{
y = sqrt(x);
printf("%lf\t %lf\n", x, y);
}
count = count + 1;

if (count <= 5)
goto read;
printf("\nEnd of computation");
}



Output

Enter FIVE real values in a LINE
50.70 40 -36 75 11.25
50.750000 7.123903
40.000000 6.324555
Value -3 is negative
75.000000 8.660254
11.250000 3.354102
End of computation

Fig.5.13 Use of the goto statement