You are on page 1of 69

Array 211 212 Programming in C

1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10
worked-out proBlem 8.1 E
Write a program using a single-subscripted variable to evaluate the following expressions: x[ 1] = 1.10
10
x[ 2] = 2.20
Total =
Âx
i=1
2
i x[ 3] = 3.30
x[ 4] = 4.40
The values of x1,x2,....are read from the terminal.
x[ 5] = 5.50
Program in Fig. 8.1 uses a one-dimensional array x to read the values and compute the sum of their x[ 6] = 6.60
squares. x[ 7] = 7.70
x[ 8] = 8.80
Program x[ 9] = 9.90
main() x[10] = 10.10
{
int i ; Total = 446.86
float x[10], value, total ;
Fig. 8.1 Program to illustrate one-dimensional array
/* . . . . . .READING VALUES INTO ARRAY . . . . . . */
Note C99 permits arrays whose size can be specified at run time. See Appendix “C99 Features”.
printf(“ENTER 10 REAL NUMBERS\n”) ;

for( i = 0 ; i < 10 ; i++ ) INITIALIZATION OF ONE-DIMENSIONAL ARRAYS


{ After an array is declared, its elements must be initialized. Otherwise, they will contain “garbage”. An
scanf(“%f”, &value) ; array can be initialized at either of the following stages:
x[i] = value ; ∑ At compile time
} ∑ At run time
/* . . . . . . .COMPUTATION OF TOTAL . . . . . . .*/
Compile time initialization
total = 0.0 ; We can initialize the elements of arrays in the same way as the ordinary variables when they are
for( i = 0 ; i < 10 ; i++ ) declared. The general form of initialization of arrays is:
total = total + x[i] * x[i] ; type array-name[size] = { list of values };
The values in the list are separated by commas. For example, the statement
/*. . . . PRINTING OF x[i] VALUES AND TOTAL . . . */ int number[3] = { 0,0,0 };
will declare the variable number as an array of size 3 and will assign zero to each element. If the
printf(“\n”); number of values in the list is less than the number of elements, then only that many elements will be
for( i = 0 ; i < 10 ; i++ ) initialized. The remaining elements will be set to zero automatically. For instance,
printf(“x[%2d] = %5.2f\n”, i+1, x[i]) ; float total[5] = {0.0,15.75,–10};
will initialize the first three elements to 0.0, 15.75, and –10.0 and the remaining two elements to zero.
printf(“\ntotal = %.2f\n”, total) ; The size may be omitted. In such cases, the compiler allocates enough space for all initialized
} elements. For example, the statement
Output int counter[ ] = {1,1,1,1};
ENTER 10 REAL NUMBERS will declare the counter array to contain four elements with initial values 1. This approach works fine as
long as we initialize every element in the array.
E for Easy, M for Medium and H for High
214 Programming in C Array 215

m }
worked-out proBlem 8.2
Output
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
43 65 51 27 79 11 56 61 82 09 25 36 07 49 55 63 74 81 49 37
81 49 37 40 49 16 75 87 91 33 24 58 78 65 56 76 67 (Input data)
40 49 16 75 87 91 33 24 58 78 65 56 76 67 45 54 36 63 12 21
45 54 36 63 12 21 73 49 51 19 39 49 68 93 85 59
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: GROUP RANGE FREQUENCY
0–9, 10–19, 20–29,.....,100. 1 0 to 9 2
2 10 to 19 4
The program coded in Fig. 8.2 uses the array group containing 11 elements, one for each range of 3 20 to 29 4
marks. Each element counts those values falling within the range of values it represents. 4 30 to 39 5
For any value, we can determine the correct group element by dividing the value by 10. For example,
5 40 to 49 8
consider the value 59. The integer division of 59 by 10 yields 5. This is the element into which 59 is
counted. 6 50 to 59 8
7 60 to 69 7
Program 8 70 to 79 6
#define MAXVAL 50 9 80 to 89 4
#define COUNTER 11 10 90 to 99 2
main() 11 100 to 100 0
{
float value[MAXVAL]; Fig. 8.2 Program for frequency counting
int i, low, high; Note that we have used an initialization statement.
int group[COUNTER] = {0,0,0,0,0,0,0,0,0,0,0}; int group [COUNTER] = {0,0,0,0,0,0,0,0,0,0,0};
/* . . . . . . . .READING AND COUNTING . . . . . .*/ which can be replaced by
for( i = 0 ; i < MAXVAL ; i++ ) int group [COUNTER] = {0};
{ This will initialize all the elements to zero.
/*. . . . . . . .READING OF VALUES . . . . . . . . */
scanf(“%f”, &value[i]) ; worked-out proBlem 8.3 H
/*. . . . . .COUNTING FREQUENCY OF GROUPS. . . . . */
The program shown in Fig. 8.3 shows the algorithm, flowchart and the complete C program to find
++ group[ (int) ( value[i]) / 10] ;
the two’s compliment of a binary number.
}
/* . . . .PRINTING OF FREQUENCY TABLE . . . . . . .*/
printf(“\n”); Algorithm
printf(“ GROUP RANGE FREQUENCY\n\n”) ; Step 1 – Start
for( i = 0 ; i < COUNTER ; i++ ) Step 2 – Read a binary number string (a[])
{ Step 3 – Calculate the length of string str (len)
low = i * 10 ; Step 4 – Initialize the looping counter k=0
if(i == 10) Step 5 – Repeat Steps 6-8 while a[k] != ‘\0’
high = 100 ; Step 6 – If a[k]!= 0 AND a[k]!= 1 goto Step 7 else goto Step 8
else Step 7 – Display error “Incorrect binary number format” and terminate the program
high = low + 9 ; Step 8 – k = k + 1
printf(“ %2d %3d to %3d %d\n”, Step 9 – Initialize the looping counter i = len - 1
i+1, low, high, group[i] ) ; Step 10 – Repeat Step 11 while a[i]!=’1’
} Step 11 – i = i - 1
216 Programming in C Array 217

Step 12 – Initialize the looping counter j = i - 1 gets(a);


Step 13 – Repeat Step 14-17 while j >= 0 len=strlen(a);
Step 14 – If a[j]=1 goto Step 15 else goto Step 16 for(k=0;a[k]!=’\0’; k++)
Step 15 – a[j]=’0’ {
Step 16 – a[j]=’1’ if (a[k]!=’0’ && a[k]!=’1’)
Step 17 – j = j - 1 {
Step 18 – Display a[] as the two’s compliment printf(“\nIncorrect binary number format...the program will quit”);
Step 19 – Stop getch();
exit(0);
Flowchart
}
Start }
Is a[i]!=1?
No for(i=len-1;a[i]!=’1’; i--)
Read binary number a[] ;
Yes for(j=i-1;j>=0;j--)
len = strlen(a) i=i–1 {
k=0
if(a[j]==’1’)
a[j]=’0’;
Is No j=i–1
a[k]!='\0'?
i = len – 1 else
a[j]=’1’;
k=k+1 Yes
Is j>=0? No }
Is a[k]!=0 Yes printf(“\n2’s compliment = %s”,a);
& a[k]!=1? j=j–1 getch();
Yes Display a[] as
the two's compliment
No }
Display "Incorrect No
binary number format" Is a[j]=1? Output
Enter a binary number: 01011001001
Yes 2’s compliment = 10100110111
a[j]= 0 a[j] = 1

Fig. 8.3 Algorithm, flowchart and C program to find two’s compliment of a binary number

Stop
Searching and Sorting
Searching and sorting are the two most frequent operations performed on arrays. Computer Scientists
Program have devised several data structures and searching and sorting techniques that facilitate rapid access
#include <stdio.h> to data stored in lists.
#include <conio.h> Sorting is the process of arranging elements in the list according to their values, in ascending or
#include <string.h> descending order. A sorted list is called an ordered list. Sorted lists are especially important in list
void main() searching because they facilitate rapid search operations. Many sorting techniques are available. The
three simple and most important among them are:
{
char a[16]; ∑ Bubble sort
int i,j,k,len; ∑ Selection sort
∑ Insertion sort
clrscr();
Other sorting techniques include Shell sort, Merge sort and Quick sort.
printf(“Enter a binary number: “);
Array 219 220 Programming in C

Column0 Column1 Column2


printf(“ MULTIPLICATION TABLE\n\n”) ;
printf(“ “) ;
[0[ [0[ [0[ [1[ [0[ [2[ for( j = 1 ; j <= COLUMNS ; j++ )
printf(“%4d” , j ) ;
Row 0 310 275 365 printf(“\n”) ;
printf(“——————————————————————————————\n”);
[1[ [ 0[ [1[[1[ [1 [[ 2 [ for( i = 0 ; i < ROWS ; i++ )
{
Row 1 10 190 325 row = i + 1 ;
printf(“%2d |”, row) ;
[ 2[ [ 0[ [ 2 [ [1 [ [ 2[[ 2 [
for( j = 1 ; j <= COLUMNS ; j++ )
{
Row 2 405 235 240 column = j ;
product[i][j] = row * column ;
[3[[ 0 [ [3 [ [1 [ [3[[2[
printf(“%4d”, product[i][j] ) ;
Row 3
}
310 275 365
printf(“\n”) ;
}
Fig. 8.4 Representation of a two-dimensional array in memory
}
Output
worked-out proBlem 8.4 L MULTIPLICATION TABLE
1 2 3 4 5
Write a program to compute and print a multiplication table for numbers 1 to 5 as shown
below. 1 1 2 3 4 5
1 2 3 4 5 2 2 4 6 8 10
1 1 2 3 4 5 3 3 6 9 12 15
2 2 4 6 8 10
4 4 8 12 16 20
3 3 6 . . .
4 4 8 . . . 5 5 10 15 20 25
5 5 10 . . 25
Fig. 8.5 Program to print multiplication table using two-dimensional array
The program shown in Fig. 8.6 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 worked-out proBlem 8.5 H
where i denotes rows and j denotes columns of the product table. Since the indices i and j range from 0
Write a program using a two-dimensional array to compute and print the following information
to 4, we have introduced the following transformation:
from the table of data discussed above:
row = i+1
(a) Total value of sales by each girl.
column = j+1
(b) Total value of each item sold.
(c) Grand total of sales of all items by all girls.
Program
#define ROWS 5 The program and its output are shown in Fig. 8.5. The program uses the variable value in two-
#define COLUMNS 5 dimensions with the index i representing girls and j representing items. The following equations are
main() used in computing the results:
{ 2
(a) Total sales by mth girl =
int row, column, product[ROWS][COLUMNS] ;
int i, j ;
 value [m][j] (girl_total[m])
j =0
Array 221 222 Programming in C

3 /*.......COMPUTING grand_total.........................*/
(b) Total value of nth item =
 value [i][n] (item_total[n])
i =0
grand_total = 0;
for( i =0 ; i < MAXGIRLS ; i++ )
3 2
grand_total = grand_total + girl_total[i];
(c) Grand total =
  value[i][j]
i =0 j =0
/* .......PRINTING OF RESULTS...........................*/
3
printf(“\n GIRLS TOTALS\n\n”);
= Â girl_total[i]
i =0
2 for( i = 0 ; i < MAXGIRLS ; i++ )
= Â
j =0
item_total[j] printf(“Salesgirl[%d] = %d\n”, i+1, girl_total[i] );
printf(“\n ITEM TOTALS\n\n”);
for( j = 0 ; j < MAXITEMS ; j++ )
Program printf(“Item[%d] = %d\n”, j+1 , item_total[j] );
#define MAXGIRLS 4 printf(“\nGrand Total = %d\n”, grand_total);
#define MAXITEMS 3 }
main() Output
{ Input data
int value[MAXGIRLS][MAXITEMS]; Enter values, one at a time, row_wise
int girl_total[MAXGIRLS] , item_total[MAXITEMS]; 310 257 365
int i, j, grand_total; 210 190 325
/*.......READING OF VALUES AND COMPUTING girl_total ...*/ 405 235 240
260 300 380
printf(“Input data\n”); GIRLS TOTALS
printf(“Enter values, one at a time, row-wise\n\n”); Salesgirl[1] = 950
Salesgirl[2] = 725
for( i = 0 ; i < MAXGIRLS ; i++ ) Salesgirl[3] = 880
{ Salesgirl[4] = 940
girl_total[i] = 0; ITEM TOTALS
for( j = 0 ; j < MAXITEMS ; j++ ) Item[1] = 1185
{ Item[2] = 1000
scanf(“%d”, &value[i][j]); Item[3] = 1310
girl_total[i] = girl_total[i] + value[i][j]; Grand Total = 3495
}
} Fig. 8.6 Illustration of two-dimensional arrays
/*.......COMPUTING item_total..........................*/
INITIALIZING TWO-DIMENSIONAL ARRAYS
for( j = 0 ; j < MAXITEMS ; j++ )
LO 8.4 A Like the one-dimensional arrays, two-dimensional arrays may be initialized
{
discuss how two- by following their declaration with a list of initial values enclosed in braces.
item_total[j] = 0; For example,
dimensional array is
for( i =0 ; i < MAXGIRLS ; i++ ) int table[2][3] = { 0,0,0,1,1,1};
declared and initialized
item_total[j] = item_total[j] + value[i][j];
}
Array 223 224 Programming in C

initializes the elements of the first row to zero and the second row to one. The initialization is done row Codes represent the following information:
by row. The above statement can be equivalently written as M – Madras 1 – Ambassador
int table[2][3] = {{0,0,0}, {1,1,1}}; D – Delhi 2 – Fiat
by surrounding the elements of the each row by braces. C – Calcutta 3 – Dolphin
We can also initialize a two-dimensional array in the form of a matrix as shown below: B – Bombay 4 – Maruti
int table[2][3] = { Write a program to produce a table showing popularity of various cars in four cities.
{0,0,0},
{1,1,1} 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 5 × 5 and all the elements are
Note the syntax of the above statements. Commas are required after each brace that closes off a
initialized to zero.
row, except in the case of the last row.
The program shown in Fig. 8.7 reads the city code and the car code, one set after another, from the
When the array is completely initialized with all values, explicitly, we need not specify the size of the
terminal. Tabulation ends when the letter X is read in place of a city code.
first dimension. That is, the statement
int table [ ] [3] = { Program
{ 0, 0, 0}, main()
{ 1, 1, 1} {
}; int i, j, car;
is permitted. int frequency[5][5] = { {0},{0},{0},{0},{0} };
If the values are missing in an initializer, they are automatically set to zero. For instance, the
char city;
statement
printf(“For each person, enter the city code \n”);
int table[2][3] = {
printf(“followed by the car code.\n”);
{1,1},
printf(“Enter the letter X to indicate end.\n”);
{2} /*. . . . . . TABULATION BEGINS . . . . . */
}; for( i = 1 ; i < 100 ; i++ )
will initialize the first two elements of the first row to one, the first element of the second row to two, and
{
all other elements to zero.
scanf(“%c”, &city );
When all the elements are to be initialized to zero, the following short-cut method may be used.
if( city == ‘X’ )
int m[3][5] = { {0}, {0}, {0}};
break;
The first element of each row is explicitly initialized to zero while other elements are automatically
initialized to zero. The following statement will also achieve the same result: scanf(“%d”, &car );
switch(city)
int m [3] [5] = { 0, 0};
{
case ‘B’ : frequency[1][car]++;
worked-out proBlem 8.6 m break;
A survey to know the popularity of four cars (Ambassador, Fiat, Dolphin and Maruti) was conducted case ‘C’ : frequency[2][car]++;
in four cities (Bombay, Calcutta, Delhi and Madras). Each person surveyed was asked to give his city break;
and the type of car he was using. The results, in coded form, are tabulated as follows: case ‘D’ : frequency[3][car]++;
break;
M 1 C 2 B 1 D 3 M 2 B 4
case ‘M’ : frequency[4][car]++;
C 1 D 3 M 4 B 2 D 1 C 3
D 4 D 4 M 1 M 1 B 3 B 3 break;
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 /*. . . . .TABULATION COMPLETED AND PRINTING BEGINS. . . .*/
printf(“\n\n”);
printf(“ POPULARITY TABLE\n\n”);
Array 225 226 Programming in C

printf(“——————————————————————————————–————–\n”); memory layout


printf(“City Ambassador Fiat Dolphin Maruti \n”);
The subscripts in the definition of a two-dimensional array represent rows and columns. This format
printf(“———————————————————————————————————–\n”);
maps the way that data elements are laid out in the memory. The elements of all arrays are stored
for( i = 1 ; i <= 4 ; i++ ) contiguously in increasing memory locations, essentially in a single list. If we consider the memory as a
{ row of bytes, with the lowest address on the left and the highest address on the right, a simple array will
switch(i) be stored in memory with the first element at the left end and the last element at the right end. Similarly,
{ a two-dimensional array is stored “row-wise, starting from the first row and ending with the last row,
case 1 : printf(“Bombay “) ; treating each row like a simple array. This is illustrated below.
break ; Column
case 2 : printf(“Calcutta “) ; 0 1 2
break ;
0 10 20 30
case 3 : printf(“Delhi “) ;
break ; row 1 40 50 60 3 ¥ 3 array
case 4 : printf(“Madras “) ;
2 70 80 90
break ;
}
row 0 row 1 row 2
for( j = 1 ; j <= 4 ; j++ )
printf(“%7d”, frequency[i][j] ) ; 10 20 30 40 50 60 70 80 90
printf(“\n”) ;
[0][0] [0][1] [0][2] [1][0] [1][1] [1][2] [2][0] [2][1] [2][2]
} 1 2 3 4 5 6 7 8 9
printf(“——————————————————————————————————————————\n”);
/*. . . . . . . . . PRINTING ENDS. . . . . . . . . . .*/ Memory Layout
} For a multi-dimensional array, the order of storage is that the first element stored has 0 in all its
Output subscripts, the second has all of its subscripts 0 except the far right which has a value of 1 and so on.
The elements of a 2 x 3 x 3 array will be stored as under
For each person, enter the city code
followed by the car code. 1 2 3 4 5 6 7 8 9
Enter the letter X to indicate end. 000 001 002 010 011 012 020 021 022
M 1 C 2 B 1 D 3 M 2 B 4
10 11 12 13 14 15 16 17 18
C 1 D 3 M 4 B 2 D 1 C 3
D 4 D 4 M 1 M 1 B 3 B 3 100 101 102 110 111 112 120 121 122
... ...
C 1 C 1 C 2 M 4 M 4 C 2
The far right subscript increments first and the other subscripts increment in order from right to left.
D 1 C 2 B 3 M 1 B 1 C 2
The sequence numbers 1, 2,……, 18 represents the location of that element in the list.
D 3 M 4 C 1 D 2 M 3 B 4 X
POPULARITY TABLE

City Ambassador Fiat Dolphin Maruti worked-out proBlem 8.7 E


The program in Fig. 8.9 shows how to find the transpose of a matrix.
Bombay 2 1 3 2
Calcutta 4 5 1 0 Algorithm
Delhi 2 1 3 2 Step 1 – Start
Madras 4 1 1 4
Step 2 – Read a 3 X 3 matrix (a[3][3])
Step 3 – Initialize the looping counter i = 0
Step 4 – Repeat Steps 5-9 while i<3
Fig. 8.7 Program to tabulate a survey data
Array 227 228 Programming in C

Step 5 – Initialize the looping counter j = 0 {


Step 6 – Repeat Steps 7-8 while j<3 printf(“\n”);
Step 7 – b[i][j]=a[j][i] for(j=0;j<3;j++)
Step 8 – j = j + 1 {
Step 9 – i = i + 1 printf(“%d\t”,b[i][j]);
Step 10 – Display b[][] as the transpose of the matrix a[][] }
Step 11 – Stop }
Flowchart getch();
Program }
#include <stdio.h> Output
#include <conio.h> Enter a 3 X 3 matrix:
void main() a[0][0] = 1
{ a[0][1] = 2
int i,j,a[3][3],b[3][3]; a[0][2] = 3
clrscr(); a[1][0] = 4
printf(“Enter a 3 X 3 matrix:\n”); a[1][1] = 5
for(i=0;i<3;i++) a[1][2] = 6
{ a[2][0] = 7
for(j=0;j<3;j++) Start
a[2][1] = 8
{ a[2][2] = 9
printf(“a[%d][%d] = “,i,j); Read a[3][3] The entered matrix is:
scanf(“%d”,&a[i][j]); 1 2 3
} i=0 4 5 6
} 7 8 9
printf(“\nThe entered matrix The transpose of the matrix is:
No Display b[] [] as the
Is i < 3?
is: \n”); transpose of a[] [] 1 4 7
for(i=0;i<3;i++) Yes
2 5 8
{ j=0
3 6 9
i=i+1
printf(“\n”);
Fig. 8.8 Program to find transpose of a matrix
for(j=0;j<3;j++)
No
{ Is j < 3? Stop
printf(“%d\t”,a[i][j]); m
Yes worked-out proBlem 8.8
} j=j+1

}
b[i][j]=a[j][i] The program in Fig. 8.8 shows how to multiply the elements of two N ¥ N matrices.
for(i=0;i<3;i++)
{ Program
for(j=0;j<3;j++) #include<stdio.h>
b[i][j]=a[j][i]; #include<conio.h>
} void main()
printf(“\n\nThe transpose of the matrix is: \n”); {
int a1[10][10],a2[10][10],c[10][10],i,j,k,a,b;
for(i=0;i<3;i++) clrscr();
Array 229 230 Programming in C

printf(“Enter the size of the square matrix\n”); for(j=0;j<b;j++)


scanf (“%d”, &a); printf(“ %d “,c[i][j]);
b=a; }
printf(“You have to enter the matrix elements in row-wise fashion\n”); getch();
for(i=0;i<a;i++) }
{ Output
for(j=0;j<b;j++) Enter the size of the square matrix
{ 2
printf(“\nEnter the next element in the 1st matrix=”); You have to enter the matrix elements in row-wise fashion
scanf(“%d”,&a1[i][j]); Enter the next element in the 1st matrix=1
} Enter the next element in the 1st matrix=0
} Enter the next element in the 1st matrix=2
for(i=0;i<a;i++) Enter the next element in the 1st matrix=3
{ Enter the next element in the 2nd matrix=4
for(j=0;j<b;j++) Enter the next element in the 2nd matrix=5
{ Enter the next element in the 2nd matrix=0
printf(“\n\nEnter the next element in the 2nd matrix=”); Enter the next element in the 2nd matrix=2
scanf(“%d”,&a2[i][j]); Entered matrices are
} 1 0
} 2 3
printf(“\n\nEntered matrices are\n”); 4 5
for(i=0;i<a;i++) 0 2
{ printf(“\n”); Product of the two matrices is
for(j=0;j<b;j++) 4 5
printf(“ %d “,a1[i][j]); 8 16
} Fig. 8.9 Program for N ¥ N matrix multiplication
printf(“\n”);
for(i=0;i<a;i++)
{ printf(“\n”); MULTI-DIMENSIONAL ARRAYS
for(j=0;j<b;j++) C allows arrays of three or more dimensions. The exact limit is determined
LO 8.5
printf(“ %d “,a2[i][j]); by the compiler. The general form of a multi-dimensional array is
describe multi-
} type array_name[s1][s2][s3]....[sm];
dimensional arrays
printf(“\n\nProduct of the two matrices is\n”); where si is the size of the ith dimension. Some example are:
for(i=0;i<a;i++) int survey[3][5][12];
for(j=0;j<b;j++) float table[5][4][5][3];
{ survey is a three-dimensional array declared to contain 180 integer type elements. Similarly table is a
c[i][j]=0; four-dimensional array containing 300 elements of floating-point type.
The array survey may represent a survey data of rainfall during the last three years from January to
for(k=0;k<a;k++)
December in five cities.
c[i][j]=c[i][j]+a1[i][k]*a2[k][j];
If the first index denotes year, the second city and the third month, then the element survey[2][3][10]
} denotes the rainfall in the month of October during the second year in city-3.
for(i=0;i<a;i++)
{ printf(“\n”);
234 Programming in C Array 235

Initial After After After printf(“Enter the number of items\n”);


values step 1 step 2 step 3
scanf(“%d”, &n);
/* Reading items into array a */
80 35 35 35
printf(“Input %d values \n”,n);
for (i = 1; i <= n ; i++)
35 80 65 65
scanf(“%f”, &a[i]);
Trip-1
/* Sorting begins */
65 65 80 15 for (i = 1 ; i <= n–1 ; i++)
{ /* Trip-i begins */
10 10 10 80 for (j = 1 ; j <= n–i ; j++)
{
if (a[j] <= a[j+1])
35 35 35 { /* Interchanging values */
t = a[j];
65 80 80 a[j] = a[j+1];
Trip-2 a[j+1] = t;
10 65 65 }
else
80 10 10
continue ;
}
} /* sorting ends */
/* calculation of median */
35 10 if ( n % 2 == 0)
median = (a[n/2] + a[n/2+1])/2.0 ;
10 35 else
Trip-3 median = a[n/2 + 1];
65 65
/* Printing */
for (i = 1 ; i <= n ; i++)
80 80
printf(“%f “, a[i]);
printf(“\n\nMedian is %f\n”, median);
During the first trip, three pairs of items are compared and interchanged whenever needed. It should }
be noted that the number 80, the largest among the items, has been moved to the bottom at the end of Output
the first trip. This means that the element 80 (the last item in the new list) need not be considered any Enter the number of items
further. Therefore, trip-2 requires only two pairs to be compared. This time, the number 65 (the second 5
largest value) has been moved down the list. Notice that each trip brings the smallest value 10 up by Input 5 values
one level. 1.111 2.222 3.333 4.444 5.555
The number of steps required in a trip is reduced by one for each trip made. The entire process will be 5.555000 4.444000 3.333000 2.222000 1.111000
over when a trip contains only one step. If the list contains n elements, then the number of comparisons Median is 3.333000
involved would be n(n–1)/2. Enter the number of items
6
Program Input 6 values
#define N 10 3 5 8 9 4 6
main( ) 9.000000 8.000000 6.000000 5.000000 4.000000 3.000000
{ Median is 5.500000
int i,j,n;
float median,a[N],t; Fig. 8.10 Program to sort a list of numbers and to determine median
236 Programming in C Array 237

2. Calculation of Standard Deviation [LO 8.2, M] }


In statistics, standard deviation is used to measure deviation of data from its mean. The formula for variance = sumsqr/(float)n ;
calculating standard deviation of n items is stddeviation = sqrt(variance) ;
s= printf(“\nNumber of items : %d\n”,n);
variance
where printf(“Mean : %f\n”, mean);
n printf(“Standard deviation : %f\n”, stddeviation);
1
variance =
n  ( x - m)
i=1
i
2

Output
}

and Input values: input -1 to end


n 65 9 27 78 12 20 33 49 -1
1
m = mean =
n Âx
i=1
i
Number of items : 8

The algorithm for calculating the standard deviation is as follows: Mean : 36.625000
1. Read n items. Standard deviation : 23.510303
2. Calculate sum and mean of the items.
3. Calculate variance. Fig. 8.11 Program to calculate standard deviation
4. Calculate standard deviation.
Complete program with sample output is shown in Fig. 8.11.
3. Evaluating a Test [LO 8.2, H]
Program A test consisting of 25 multiple-choice items is administered to a batch of 3 students. Correct answers
#include <math.h> and student responses are tabulated as shown below:
#define MAXSIZE 100 Items
main( )
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
{ Correct
int i,n; answers
float value [MAXSIZE], deviation,
sum,sumsqr,mean,variance,stddeviation; Student 1
sum = sumsqr = n = 0 ;
Student 2
printf(“Input values: input –1 to end \n”);
for (i=1; i< MAXSIZE ; i++) Student 3

{
scanf(“%f”, &value[i]); The algorithm for evaluating the answers of students is as follows:
if (value[i] == -1) 1. Read correct answers into an array.
break; 2. Read the responses of a student and count the correct ones.
sum += value[i]; 3. Repeat step-2 for each student.
n += 1; 4. Print the results.
} A program to implement this algorithm is given in Fig. 8.12. The program uses the following arrays:
mean = sum/(float)n; key[i] - To store correct answers of items
for (i = 1 ; i<= n; i++) response[i] - To store responses of students
correct[i] - To identify items that are answered correctly.
{
deviation = value[i] – mean;
sumsqr += deviation * deviation;
238 Programming in C Array 239

Program if(correct[i] == 0)
#define STUDENTS 3 {
#define ITEMS 25 printf(“%d “,i+1);
main( ) n = n+1;
{ }
char key[ITEMS+1],response[ITEMS+1]; if(n == 0)
int count, i, student,n, printf(“NIL\n”);
correct[ITEMS+1]; printf(“\n”);
/* Reading of Correct answers */ } /* Go to next student */
printf(“Input key to the items\n”); /* Evaluation and printing ends */
for(i=0; i < ITEMS; i++) }
scanf(“%c”,&key[i]); Output
scanf(“%c”,&key[i]); Input key to the items
key[i] = ‘\0’; abcdabcdabcdabcdabcdabcda
/* Evaluation begins */ Input responses of student-1
for(student = 1; student <= STUDENTS ; student++) abcdabcdabcdabcdabcdabcda
{ Student-1
/*Reading student responses and counting correct ones*/ Score is 25 out of 25
count = 0; Response to the following items are wrong
printf(“\n”); NIL
printf(“Input responses of student-%d\n”,student); Input responses of student-2
for(i=0; i < ITEMS ; i++) abcddcbaabcdabcdddddddddd
scanf(“%c”,&response[i]); Student-2
scanf(“%c”,&response[i]); Score is 14 out of 25
response[i] = ‘\0’; Response to the following items are wrong
for(i=0; i < ITEMS; i++) 5 6 7 8 17 18 19 21 22 23 25
correct[i] = 0; Input responses of student-3
for(i=0; i < ITEMS ; i++) aaaaaaaaaaaaaaaaaaaaaaaaa
if(response[i] == key[i]) Student-3
{ Score is 7 out of 25
count = count +1 ; Response to the following items are wrong
correct[i] = 1 ; 2 3 4 6 7 8 10 11 12 14 15 16 18 19 20 22 23 24
}
Fig. 8.12 Program to evaluate responses to a multiple-choice test
/* printing of results */
printf(“\n”);
4. Production and Sales Analysis [LO 8.3, 8.4, H]
printf(“Student-%d\n”, student);
printf(“Score is %d out of %d\n”,count, ITEMS); A company manufactures five categories of products and the number of items manufactured and sold
printf(“Response to the items below are wrong\n”); are recorded product-wise every week in a month. The company reviews its production schedule at
every month-end. The review may require one or more of the following information:
n = 0;
(a) Value of weekly production and sales.
for(i=0; i < ITEMS ; i++)
(b) Total value of all the products manufactured.
(c) Total value of all the products sold.
(d) Total value of each product, manufactured and sold.
240 Programming in C Array 241

Let us represent the products manufactured and sold by two two-dimensional arrays M and S 4 5
respectively. Then,
M11 M12 M13 M14 M15
= Â
i=1
Sweek[i] = Â
j=1
Sproduct[j]

M= M21 M22 M23 M24 M25


Program
M31 M32 M33 M34 M35
main( )
M41 M42 M43 M44 M45 {
int M[5][6],S[5][6],C[6],
S11 S12 S13 S14 S15
Mvalue[5][6],Svalue[5][6],
S= S21 S22 S23 S24 S25
Mweek[5], Sweek[5],
S31 S32 S33 S34 S35 Mproduct[6], Sproduct[6],
S41 S42 S43 S44 S45 Mtotal, Stotal, i,j,number;
/* Input data */
where Mij represents the number of jth type product manufactured in ith week and Sij the number of jth
printf (“ Enter products manufactured week_wise \n”);
product sold in ith week. We may also represent the cost of each product by a single dimensional array
printf (“ M11,M12,——, M21,M22,—— etc\n”);
C as follows:
C= C1 C2 C3 C4 C5 for(i=1; i<=4; i++)
for(j=1;j<=5; j++)
where Cj is the cost of jth type product.
scanf(“%d”,&M[i][j]);
We shall represent the value of products manufactured and sold by two value arrays, namely, Mvalue
and Svalue. Then, printf (“ Enter products sold week_wise\n”);
Mvalue[i][j] = Mij x Cj printf (“ S11,S12,——, S21,S22,—— etc\n”);
Svalue[i][j] = Sij x Cj
A program to generate the required outputs for the review meeting is shown in Fig. 8.13. The following for(i=1; i<=4; i++)
additional variables are used: for(j=1; j<=5; j++)
Mweek[i] = Value of all the products manufactured in week i scanf(“%d”, &S[i][j]);
5

= Â
J=1
Mvalue[i][j]
printf(“ Enter cost of each product\n”);
for(j=1; j <=5; j++)
Sweek[i] = Value of all the products in week i scanf(“%d”,&C[j]);
5
/* Value matrices of production and sales */
= Â
J=1
Svalue[i][j]
for(i=1; i<=4; i++)
Mproduct[j] = Value of jth type product manufactured during the month for(j=1; j<=5; j++)
4
{
= Â
i=1
Mvalue[i][j]
Mvalue[i][j] = M[i][j] * C[j];
Sproduct[j] = Value of jth type product sold during the month Svalue[i][j] = S[i][j] * C[j];
4
}
= Â
i=1
Svalue[i][j] /* Total value of weekly production and sales */

Mtotal = Total value of all the products manufactured during the month for(i=1; i<=4; i++)
4 5 {
= Âi=1
Mweek[i] = Âj=1
Mproduct[j] Mweek[i] = 0 ;
Sweek[i] = 0 ;
Stotal = Total value of all the products sold during the month
for(j=1; j<=5; j++)
242 Programming in C Array 243

{ { /* Beginning of while loop */


Mweek[i] += Mvalue[i][j]; printf(“\n\n ENTER YOUR CHOICE:”);
scanf(“%d”,&number);
Sweek[i] += Svalue[i][j];
printf(“\n”);
}
if(number == 5)
} {
/* Monthly value of product_wise production and sales */ printf(“ G O O D B Y E\n\n”);
for(j=1; j<=5; j++) break;
}
{
switch(number)
Mproduct[j] = 0 ;
{ /* Beginning of switch */
Sproduct[j] = 0 ; /* V A L U E M A T R I C E S */
for(i=1; i<=4; i++) case 1:
{ printf(“ VALUE MATRIX OF PRODUCTION\n\n”);
Mproduct[j] += Mvalue[i][j]; for(i=1; i<=4; i++)
{
Sproduct[j] += Svalue[i][j];
printf(“ Week(%d)\t”,i);
} for(j=1; j <=5; j++)
} printf(“%7d”, Mvalue[i][j]);
/* Grand total of production and sales values */ printf(“\n”);
Mtotal = Stotal = 0; }
printf(“\n VALUE MATRIX OF SALES\n\n”);
for(i=1; i<=4; i++)
for(i=1; i <=4; i++)
{ {
Mtotal += Mweek[i]; printf(“ Week(%d)\t”,i);
Stotal += Sweek[i]; for(j=1; j <=5; j++)
} printf(“%7d”, Svalue[i][j]);
/*********************************************** printf(“\n”);
Selection and printing of information required }
***********************************************/ break;
printf(“\n\n”); /* W E E K L Y A N A L Y S I S */
printf(“ Following is the list of things you can\n”); case 2:
printf(“ request for. Enter appropriate item number\n”); printf(“ TOTAL WEEKLY PRODUCTION & SALES\n\n”);
printf(“ and press RETURN Key\n\n”); printf(“ PRODUCTION SALES\n”);
printf(“ 1.Value matrices of production & sales\n”); printf(“ ————— —— \n”);
printf(“ 2.Total value of weekly production & sales\n”); for(i=1; i <=4; i++)
printf(“ 3.Product_wise monthly value of production &”); {
printf(“ sales\n”); printf(“ Week(%d)\t”, i);
printf(“ 4.Grand total value of production & sales\n”); printf(“%7d\t%7d\n”, Mweek[i], Sweek[i]);
printf(“ 5.Exit\n”); }
number = 0; break;
while(1) /* P R O D U C T W I S E A N A L Y S I S */
244 Programming in C Array 245

case 3: and press RETURN key


printf(“ PRODUCT_WISE TOTAL PRODUCTION &”); 1.Value matrices of production & sales
printf(“ SALES\n\n”); 2.Total value of weekly production & sales
printf(“ PRODUCTION SALES\n”); 3.Product_wise monthly value of production & sales
printf(“ ————— —— \n”); 4.Grand total value of production & sales
for(j=1; j <=5; j++) 5.Exit
{ ENTER YOUR CHOICE:1
printf(“ Product(%d)\t”, j); VALUE MATRIX OF PRODUCTION
printf(“%7d\t%7d\n”,Mproduct[j],Sproduct[j]); Week(1) 110 300 360 210 325
} Week(2) 130 260 420 225 300
break; Week(3) 120 320 300 225 350
/* G R A N D T O T A L S */ Week(4) 140 220 450 185 300
case 4: VALUE MATRIX OF SALES
printf(“ GRAND TOTAL OF PRODUCTION & SALES\n”); Week(1) 100 260 270 180 275
printf(“\n Total production = %d\n”, Mtotal); Week(2) 120 200 360 210 250
printf(“ Total sales = %d\n”, Stotal); Week(3) 110 280 300 210 300
break; Week(4) 120 200 390 165 250
/* D E F A U L T */ ENTER YOUR CHOICE:2
default : TOTAL WEEKLY PRODUCTION & SALES
printf(“ Wrong choice, select again\n\n”); PRODUCTION SALE
break;
Week(1) 1305 1085
} /* End of switch */
Week(2) 1335 1140
} /* End of while loop */
Week(3) 1315 1200
printf(“ Exit from the program\n\n”);
Week(4) 1305 1125
} /* End of main */
Output ENTER YOUR CHOICE:3
Enter products manufactured week_wise PRODUCT_WISE TOTAL PRODUCTION & SALES
M11, M12, — — – –, M21, M22, ——–– etc PRODUCTION SALES
11 15 12 14 13 Product(1) 500 450
13 13 14 15 12 Product(2) 1100 940
12 16 10 15 14 Product(3) 1530 1320
14 11 15 13 12 Product(4) 855 765
Enter products sold week_wise Product(5) 1275 1075
S11,S12,— — – –, S21,S22,——–– etc ENTER YOUR CHOICE:4
10 13 9 12 11 GRAND TOTAL OF PRODUCTION & SALES
12 10 12 14 10 Total production = 5260
11 14 10 14 12 Total sales = 4550
12 10 13 11 10 ENTER YOUR CHOICE:5
Enter cost of each product GOOD BYE
10 20 30 15 25 Exit from the program
Following is the list of things you can
request for. Enter appropriate item number Fig. 8.13 Program for production and sales analysis
Character Arrays and Strings 255 256 Programming in C

2. The width w is less than the number of characters in the string. The excess characters will be
WORKED-OUT PROBLEM 9.1 E truncated and left unread.
Write a program to read a series of words from a terminal using scanf function. Consider the following statements:
char name[10];
The program shown in Fig. 9.1 reads four words and displays them on the screen. Note that the string scanf(“%5s”, name);
‘Oxford Road’ is treated as two words while the string ‘Oxford-Road’ as one word. The input string RAM will be stored as:
R A M \0 ? ? ? ? ? ?
Program
main( ) 0 1 2 3 4 5 6 7 8 9
{ The input string KRISHNA will be stored as:
char word1[40], word2[40], word3[40], word4[40];
K R I S H \0 ? ? ? ?
printf(“Enter text : \n”);
scanf(“%s %s”, word1, word2); 0 1 2 3 4 5 6 7 8 9
scanf(“%s”, word3);
Reading a Line of Text
scanf(“%s”, word4); We have seen just now that scanf with %s or %ws can read only strings without whitespaces. That is,
printf(“\n”); they cannot be used for reading a text containing more than one word. However, C supports a format
printf(“word1 = %s\nword2 = %s\n”, word1, word2); specification known as the edit set conversion code %[. .] that can be used to read a line containing a
variety of characters, including whitespaces. Recall that we have used this conversion code in Chapter 4.
printf(“word3 = %s\nword4 = %s\n”, word3, word4);
For example, the program segment
}
char line [80];
scanf(”%[^\n]”, line);
Output
printf(“%s”, line);
Enter text :
will read a line of input from the keyboard and display the same on the screen. We would very rarely
Oxford Road, London M17ED
use this method, as C supports an intrinsic string function to do this job. This is discussed in the next
word1 = Oxford section.
word2 = Road,
Using getchar and gets Functions
word3 = London We have discussed in Chapter 4 as to how to read a single character from the terminal, using the
word4 = M17ED function getchar. We can use this function repeatedly to read successive single characters from the
Enter text : input and place them into a character array. Thus, an entire line of text can be read and stored in an
array. The reading is terminated when the newline character (‘\n’) is entered and the null character is
Oxford-Road, London-M17ED United Kingdom
then inserted at the end of the string. The getchar function call takes the following form:
word1 = Oxford-Road
word2 = London-M17ED char ch;
word3 = United ch = getchar( );
word4 = Kingdom Note that the getchar function has no parameters.
Fig. 9.1 Reading a series of words using scanf function
WORKED-OUT PROBLEM 9.2 M
We can also specify the field width using the form %ws in the scanf statement for reading a specified
number of characters from the input string. Example: Write a program to read a line of text containing a series of words from the terminal.
scanf(“%ws”, name);
Here, the two following things may happen: The program shown in Fig. 9.2 can read a line of text (up to a maximum of 80 characters) into the string
line using getchar function. Every time a character is read, it is assigned to its location in the string line
1. The width w is equal to or greater than the number of characters typed in. The entire string will and then tested for newline character. When the newline character is read (signalling the end of line),
be stored in the string variable. the reading loop is terminated and the newline character is replaced by the null character to indicate the
end of character string.
E for Easy, M for Medium and H for High
Character Arrays and Strings 257 258 Programming in C

When the loop is exited, the value of the index c is one number higher than the last character position The last two statements may be combined as follows:
in the string (since it has been incremented after assigning the new character to the string). Therefore, printf(“%s”, gets(line));
the index value c-1 gives the position where the null character is to be stored. (Be careful not to input more character that can be stored in the string variable used. Since C does not
check array-bounds, it may cause problems.)
Program C does not provide operators that work on strings directly. For instance we cannot assign one string
#include <stdio.h> to another directly. For example, the assignment statements.
main( ) string = “ABC”;
string1 = string2;
{
are not valid. If we really want to copy the characters in string2 into string1, we may do so on a
char line[81], character; character-by-character basis.
int c;
c = 0;
WORKED-OUT PROBLEM 9.3 M
printf(“Enter text. Press <Return> at end\n”);
do Write a program to copy one string into another and count the number of characters copied.
{
character = getchar(); The program is shown in Fig. 9.3. We use a for loop to copy the characters contained inside string2 into
the string1. The loop is terminated when the null character is reached. Note that we are again assigning
line[c] = character;
a null character to the string1.
c++;
}
Program
while(character != ‘\n’);
main( )
c = c - 1;
{
line[c] = ‘\0’; char string1[80], string2[80];
printf(“\n%s\n”, line); int i;
} printf(“Enter a string \n”);
Output printf(“?”);
Enter text. Press <Return> at end scanf(“%s”, string2);
Programming in C is interesting. for( i=0 ; string2[i] != ‘\0’; i++)
Programming in C is interesting. string1[i] = string2[i];
Enter text. Press <Return> at end string1[i] = ‘\0’;
National Centre for Expert Systems, Hyderabad. printf(“\n”);
National Centre for Expert Systems, Hyderabad. printf(“%s\n”, string1);
printf(“Number of characters = %d\n”, i );
Fig. 9.2 Program to read a line of text from terminal
}
Another and more convenient method of reading a string of text containing whitespaces is to use Output
the library function gets available in the <stdio.h> header file. This is a simple function with one string Enter a string
parameter and called as under:
?Manchester
gets (str);
str is a string variable declared properly. It reads characters into str from the keyboard until a new-line Manchester
character is encountered and then appends a null character to the string. Unlike scanf, it does not skip Number of characters = 10
whitespaces. For example the code segment Enter a string
char line [80]; ?Westminster
gets (line);
Westminster
printf (“%s”, line);
Number of characters = 11
reads a line of text from the keyboard and displays it on the screen.
Fig. 9.3 Copying one string into another
Character Arrays and Strings 259 260 Programming in C

Program
WORKED-OUT PROBLEM 9.4 H
#include <stdio.h>
The program in Fig. 9.4 shows how to write a program to find the number of vowels and consonants #include <conio.h>
in a text string. Elucidate the program and flowchart for the program. #include <string.h>
void main()
Algorithm
{
Step 1 – Start
char str[30];
Step 2 – Read a text string (str)
int vow=0,cons=0,i=0;
Step 3 – Set vow = 0, cons = 0, i = 0
clrscr();
Step 4 – Repeat steps 5-8 while (str[i]!=’\0’)
printf(“Enter a string: “);
Step 5 – if str[i] = ‘a’ OR str[i] = ‘A’ OR str[i] = ‘e’ OR str[i] = ‘E’ OR str[i] = ‘i’
OR str[i] = ‘I’ OR str[i] = ‘o’ OR str[i] = ‘O’ OR str[i] = ‘u’ OR str[i] = ‘U’ gets(str);
goto Step 6 else goto Step 7 while(str[i] != ‘\0’)
Step 6 – Increment the vowels counter by 1 (vow=vow+1) {
Step 7 – Increment the consonants counter by 1 (cons=cons+1) if(str[i]== a’ || str[i]==‘A’ || str[i]==‘e’ || str[i]==‘E’ || str[i]==‘i’
Step 8 – i = i + 1 || str[i]==‘I’ || str[i]==‘o’ || str[i]==‘O’ || str[i]==‘u’ || str[i]==‘U’)
Step 9 – Display the number of vowels and consonants (vow, cons) vow++;
Step 10 – Stop else
Flowchart cons++;
Start
i++;
}
Read text string str printf(“\nNumber of Vowels = %d”,vow);
printf(“\nNumber of Consonants = %d”,cons);
vow = 0
cons = 0 getch();
i=0 }

Yes Display vow


Is str[]= \0 ?
Display cons
Stop Output
Enter a string: Chennai
No
Number of Vowels = 3
i=i+1
Number of Consonants = 4
Fig. 9.4 Program to find the number of vowel and consonants in a text string
Is str[i] = a OR
str[i] = A OR
str[i] = e OR WRITING STRINGS TO SCReeN
str[i] = E OR No
str[i] = i OR LO 9.3 Using printf Function
str[i] = I OR
str[i] = o OR Describe how We have used extensively the printf function with %s format to print strings to
str[i] = O OR strings are written the screen. The format %s can be used to display an array of characters that is
str[i] = u OR
str[i] = U? to screen terminated by the null character. For example, the statement
printf(“%s”, name);
can be used to display the entire contents of the array name.
Yes
We can also specify the precision with which the array is displayed. For instance, the specification
%10.4
vow = vow + 1 cons = cons + 1
indicates that the first four characters are to be printed in a field width of 10 columns.
However, if we include the minus sign in the specification (e.g., %-10.4s), the string will be printed
left-justified. The Program 9.4 illustrates the effect of various %s specifications.
Character Arrays and Strings 261 262 Programming in C

WORKED-OUT PROBLEM 9.5 M WORKED-OUT PROBLEM 9.6 M


Write a program to store the string “United Kingdom” in the array country and display the string under Write a program using for loop to print the following output:
various format specifications. C
CP
The program and its output are shown in Fig. 9.5. The output illustrates the following features of the %s CPr
specifications. CPro
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 of characters to be .....
printed. CProgramming
3. When the number of characters to be printed is specified as zero, nothing is printed. CProgramming
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. .....
Program CPro
main() CPr
{ CP
char country[15] = “United Kingdom”; C
printf(“\n\n”);
The outputs of the program in Fig. 9.6, for variable specifications %12.*s, %.*s, and %*.1s are shown in
printf(“*123456789012345*\n”);
Fig. 9.7, which further illustrates the variable field width and the precision specifications.
printf(“ — — – – – \n”);
printf(“%15s\n”, country);
Program
printf(“%5s\n”, country); main()
printf(“%15.6s\n”, country); {
printf(“%-15.6s\n”, country); int c, d;
printf(“%15.0s\n”, country); char string[] = “CProgramming”;
printf(“%.3s\n”, country); printf(“\n\n”);
printf(“%s\n”, country); printf(“— — — — — — — — — — — — \n”);
printf(“——––– \n”); for( c = 0 ; c <= 11 ; c++ )
} {
Output d = c + 1;
*123456789012345* printf(“|%-12.*s|\n”, d, string);
——––– }
United Kingdom printf(“|— — — — — — — — — — — — |\n”);
United Kingdom for( c = 11 ; c >= 0 ; c— — )
United {
United d = c + 1;
Uni printf(“|%-12.*s|\n”, d, string);
United Kingdom }
——––– printf(“— — — — — — — — — — — — \n”);
}
Fig. 9.5 Writing strings using %s format Output
C
The printf on UNIX supports another nice feature that allows for variable field width or precision. For CP
instance CPr
printf(“%*.*s\n”, w, d, string); CPro
prints the first d characters of the string in the field width of w. CProg
This feature comes in handy for printing a sequence of characters. Program 9.5 illustrates this. CProgr
Character Arrays and Strings 263 Character Arrays and Strings 265

CProgra Then,
CProgram x = ASCII value of ‘7’ – ASCII value of ‘0’
CProgramm = 55 – 48
CProgrammi =7
CProgrammin The C library supports a function that converts a string of digits into their integer values. The function
CProgramming takes the form
CProgramming x = atoi(string);
CProgrammin x is an integer variable and string is a character array containing a string of digits. Consider the following
CProgrammi segment of a program:
CProgramm number = “1988”;
CProgram
year = atoi(number);
CProgra
CProgr number is a string variable which is assigned the string constant “1988”. The function atoi converts the
CProg string “1988” (contained in number) to its numeric equivalent 1988 and assigns it to the integer variable
CPro year. String conversion functions are stored in the header file <std.lib.h>.
CPr
CP
WORKED-OUT PROBLEM 9.7 E
C
Fig. 9.6 Illustration of variable field specifications by printing sequences of characters Write a program which would print the alphabet set a to z and A to Z in decimal and character form.

C C| C|
The program is shown in Fig. 9.8. In ASCII character set, the decimal numbers 65 to 90 represent upper
CP CP| C|
case alphabets and 97 to 122 represent lower case alphabets. The values from 91 to 96 are excluded
CPr CPr| C| using an if statement in the for loop.
CPro CPro| C| Program
CProg CProg| C|
main()
CProgr CProgr| C| {
CProgra CProgra| C| char c;
CProgram CProgram| C| printf(“\n\n”);
CProgramm CProgramm| C| for( c = 65 ; c <= 122 ; c = c + 1 )
CProgrammi CProgrammi| C| {
CProgrammin CProgrammin| C| if( c > 90 && c < 97 )
CProgramming CProgramming| C| continue;
CProgramming CProgramming| C| printf(“|%4d - %c “, c, c);
CProgrammin CProgrammin| C| }
CProgrammi CProgrammi| C| printf(“|\n”);
CProgramm CProgramm| C| }
CProgram CProgram| C| Output
CProgra CProgra| C| | 65 - A | 66 - B | 67 - C | 68 - D | 69 - E | 70 - F
CProgr CProgr| C| | 71 - G | 72 - H | 73 - I | 74 - J | 75 - K | 76 - L
CProg CProg| C| | 77 - M| 78 - N| 79 - O| 80 - P| 81 - Q| 82 - R
CPro CPro| C| | 83 - S| 84 - T| 85 - U| 86 - V| 87 - W| 88 - X
CPr CPr| C| | 89 - Y| 90 - Z| 97 - a| 98 - b| 99 - c| 100 - d
CP CP| C| |101 - e| 102 - f| 103 - g| 104 - h| 105 - i| 106 - j
C C| C| |107 - k| 108 - l| 109 - m| 110 - n| 111 - o| 112 - p
|113 - q| 114 - r| 115 - s| 116 - t| 117 - u| 118 - v
(a) %12.*s (b) %.*s (c) %*.1s |119 - w| 120 - x| 121 - y| 122 - z|
Fig. 9.7 Further illustrations of variable specifications Fig. 9.8 Printing of the alphabet set in decimal and character form
266 Programming in C Character Arrays and Strings 267

PUTTING STRINGS TOGeTHeR /* Copy second_name into name */


Just as we cannot assign one string to another directly, we cannot join two strings together by the simple for( j = 0 ; second_name[j] != ‘\0’ ; j++ )
arithmetic addition. That is, the statements such as name[i+j+1] = second_name[j] ;
string3 = string1 + string2; /* End second_name with a space */
string2 = string1 + “hello”; name[i+j+1] = ‘ ‘ ;
are not valid. The characters from string1 and string2 should be copied into the string3 one after the /* Copy last_name into name */
other. The size of the array string3 should be large enough to hold the total characters. for( k = 0 ; last_name[k] != ‘\0’; k++ )
The process of combining two strings together is called concatenation. Program 9.9 illustrates the name[i+j+k+2] = last_name[k] ;
concatenation of three strings. /* End name with a null character */
name[i+j+k+2] = ‘\0’ ;
printf(“\n\n”) ;
WORKED-OUT PROBLEM 9.8 M printf(“%s\n”, name) ;
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 one string to be called Output
name. VISWANATH PRATAP SINGH

The program is given in Fig. 9.9. Three for loops are used to copy the three strings. In the first loop, Fig. 9.9 Concatenation of strings
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 the assignment
statement
COMPARISON OF TWO STRINGS
name[i] = ‘ ’ ; Once again, C does not permit the comparison of two strings directly. That is, the statements such as
Similarly, the second_name is copied into name, starting from the column just after the space created if(name1 == name2)
by the above statement. This is achieved by the assignment statement if(name == “ABC”)
name[i+j+1] = second_name[j]; are not permitted. It is therefore necessary to compare the two strings to be tested, character by
If first_name contains 4 characters, then the value of i at this point will be 4 and therefore the first character. The comparison is done until there is a mismatch or one of the strings terminates into a null
character from second_name will be placed in the fifth cell of name. Note that we have stored a space character, whichever occurs first. The following segment of a program illustrates this.
in the fourth cell. i=0;
In the same way, the statement while(str1[i] == str2[i] && str1[i] != ‘\0’
name[i+j+k+2] = last_name[k]; && str2[i] != ‘\0’)
is used to copy the characters from last_name into the proper locations of name.
i = i+1;
At the end, we place a null character to terminate the concatenated string name. In this example, it
if (str1[i] == ‘\0’ && str2[i] == ‘\0’)
is important to note the use of the expressions i+j+1 and i+j+k+2.
printf(“strings are equal\n”);
Program else
main() printf(“strings are not equal\n”);
{
int i, j, k ; STRING-HANDLING FUNCTIONS
char first_name[10] = {“VISWANATH”} ;
Fortunately, the C library supports a large number of string-handling functions that can be used to carry
char second_name[10] = {“PRATAP”} ;
out many of the string manipulations discussed so far. Following are the most commonly used string-
char last_name[10] = {“SINGH”} ;
handling functions:
char name[30] ;
/* Copy first_name into name */ Function Action
for( i = 0 ; first_name[i] != ‘\0’ ; i++ ) strcat() concatenates two strings
name[i] = first_name[i] ;
strcmp() compares two strings
/* End first_name with a space */
name[i] = ‘ ‘ ; strcpy() copies one string over another
strlen() finds the length of a string
270 Programming in C Character Arrays and Strings 271

During the second run, the two strings s1 and s2 are equal, and therefore, they are not joined together.
In this case all the three strings contain the same string constant “London”. WORKED-OUT PROBLEM 9.10 M

Program The program in Fig. 9.11 shows how to write a C program that reads a string and prints if it is a
palindrome or not.
#include <string.h>
main() Program
{ char s1[20], s2[20], s3[20]; #include <stdio.h>
int x, l1, l2, l3; #include <conio.h>
printf(“\n\nEnter two string constants \n”); #include <string.h>
printf(“?”); void main()
scanf(“%s %s”, s1, s2); {
/* comparing s1 and s2 */ char chk=’t’, str[30];
x = strcmp(s1, s2); int len, left, right;
if(x != 0) printf(“\nEnter a string:”);
{ printf(“\n\nStrings are not equal \n”); scanf(“%s”, &str);
strcat(s1, s2); /* joining s1 and s2 */ len=strlen(str);
} left=0;
else right=len-1;
printf(“\n\nStrings are equal \n”); while(left < right && chk==’t’)
{
/* copying s1 to s3
if(str[left] == str[right])
strcpy(s3, s1);
;
/* Finding length of strings */
else
l1 = strlen(s1);
l2 = strlen(s2); chk=’f’;
l3 = strlen(s3); left++;
/* output */ right-;
printf(“\ns1 = %s\t length = %d characters\n”, s1, l1); }
printf(“s2 = %s\t length = %d characters\n”, s2, l2); if(chk==’t’)
printf(“s3 = %s\t length = %d characters\n”, s3, l3); printf(“\nThe string %s is a palindrome”,str);
} else
printf(“\nThe string %s is not a palindrome”,str);
Output
Enter two string constants getch();
? New York }
Strings are not equal
s1 = NewYork length = 7 characters Output
s2 = York length = 4 characters Enter a string: nitin
s3 = NewYork length = 7 characters The string nitin is a palindrome
Enter two string constants
? London London Fig. 9.11 Program to check if a string is palindrome or not
Strings are equal
s1 = London length = 6 characters Other String Functions
s2 = London length = 6 characters The header file <string.h> contains many more string manipulation functions. They might be useful in
s3 = London length = 6 characters certain situations.
Fig. 9.10 Illustration of string handling functions
274 Programming in C 276 Programming in C

“Bombay” ∑ Strings cannot be manipulated with operators. Use string functions. [LO 9.4]
} ; ∑ Do not use string functions on an array char type that is not terminated with the null character. [LO 9.4]
To access the name of the ith city in the list, we write ∑ Do not forget to append the null character to the target string when the number of characters copied
city[i-1] is less than or equal to the source string. [LO 9.4]
and therefore, city[0] denotes “Chandigarh”, city[1] denotes “Madras” and so on. This shows that ∑ Be aware the return values when using the functions strcmp and strncmp for comparing strings.
once an array is declared as two-dimensional, it can be used like a one-dimensional array in further [LO 9.4]
manipulations. That is, the table can be treated as a column of strings. ∑ When using string functions for copying and concatenating strings, make sure that the target string
has enough space to store the resulting string. Otherwise memory overwriting may occur. [LO 9.4]
∑ The header file <ctype.h> is required when using character handling functions. [LO 9.4]
WORKED-OUT PROBLEM 9.11 H ∑ The header file <string.h> is required when using string manipulation functions. [LO 9.4]
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. 9.12. It employs the method of Brief CaSeS
bubble sorting described in Case Study 1 in the previous chapter.
1. Counting Words in a Text [LO 9.1, 9.2 M]
Program
One of the practical applications of string manipulations is counting the words in a text. We assume that
#define ITEMS 5
a word is a sequence of any characters, except escape characters and blanks, and that two words are
#define MAXCHAR 20
main( ) separated by one blank character. The algorithm for counting words is as follows:
{ 1. Read a line of text.
char string[ITEMS][MAXCHAR], dummy[MAXCHAR]; 2. Beginning from the first character in the line, look for a blank. If a blank is found, increment words
int i = 0, j = 0; by 1.
/* Reading the list */
printf (“Enter names of %d items \n “,ITEMS); 3. Continue steps 1 and 2 until the last line is completed.
while (i < ITEMS) The implementation of this algorithm is shown in Fig. 9.13. The first while loop will be executed once
scanf (“%s”, string[i++]); for each line of text. The end of text is indicated by pressing the ‘Return’ key an extra time after the entire
/* Sorting begins */ text has been entered. The extra ‘Return’ key causes a newline character as input to the last line and as
for (i=1; i < ITEMS; i++) /* Outer loop begins */ a result, the last line contains only the null character.
{ The program checks for this special line using the test
for (j=1; j <= ITEMS-i ; j++) /*Inner loop begins*/ if ( line[0] == ‘\0’)
{
and if the first (and only the first) character in the line is a null character, then counting is terminated.
if (strcmp (string[j-1], string[j]) > 0)
Note the difference between a null character and a blank character.
{ /* Exchange of contents */
strcpy (dummy, string[j-1]);
strcpy (string[j-1], string[j]); Program
strcpy (string[j], dummy ); #include <stdio.h>
} main()
} /* Inner loop ends */
{
} /* Outer loop ends */
/* Sorting completed */ char line[81], ctr;
printf (“\nAlphabetical list \n\n”); int i,c,
for (i=0; i < ITEMS ; i++) end = 0,
printf (“%s”, string[i]); characters = 0,
}
words = 0,
Output
lines = 0;
Enter names of 5 items
London Manchester Delhi Paris Moscow printf(“KEY IN THE TEXT.\n”);
Alphabetical list printf(“GIVE ONE SPACE AFTER EACH WORD.\n”);
Delhi printf(“WHEN COMPLETED, PRESS ‘RETURN’.\n\n”);
London
Character Arrays and Strings 277 278 Programming in C

The program also counts the number of lines read and the total number of characters in the text.
while( end == 0)
Remember, the last line containing the null string is not counted.
{
After the first while loop is exited, the program prints the results of counting.
/* Reading a line of text */
c = 0;
while((ctr=getchar()) != ‘\n’)
2. Processing of a Customer List [LO 9.1, 9.2, 9.3, 9.4 M]
line[c++] = ctr; Telephone numbers of important customers are recorded as follows:
line[c] = ‘\0’; Full name Telephone number
/* counting the words in a line */ Joseph Louis Lagrange 869245
if(line[0] == ‘\0’) Jean Robert Argand 900823
break ; Carl Freidrich Gauss 806788
else – – –– – – – –– –
{ – – –– – – – –– –
words++; It is desired to prepare a revised alphabetical list with surname (last name) first, followed by a comma
and the initials of the first and middle names. For example,
for(i=0; line[i] != ‘\0’;i++)
Argand, J.R
if(line[i] == ‘ ‘ || line[i] == ‘\t’)
We create a table of strings, each row representing the details of one person, such as first_name,
words++; middle_name, last_name, and telephone_number. The columns are interchanged as required and the
} list is sorted on the last_name. Figure 9.14 shows a program to achieve this.
/* counting lines and characters */
lines = lines +1; Program
#define CUSTOMERS 10
characters = characters + strlen(line);
}
main( )
printf (“\n”);
{
printf(“Number of lines = %d\n”, lines);
char first_name[20][10], second_name[20][10],
printf(“Number of words = %d\n”, words);
surname[20][10], name[20][20],
printf(“Number of characters = %d\n”, characters);
telephone[20][10], dummy[20];
}
Output
KEY IN THE TEXT. int i,j;
GIVE ONE SPACE AFTER EACH WORD.
WHEN COMPLETED, PRESS ‘RETURN’. printf(“Input names and telephone numbers \n”);
Admiration is a very short-lived passion. printf(“?”);
Admiration involves a glorious obliquity of vision. for(i=0; i < CUSTOMERS ; i++)
Always we like those who admire us but we do not {
like those whom we admire. scanf(“%s %s %s %s”, first_name[i],
Fools admire, but men of sense approve. second_name[i], surname[i], telephone[i]);
Number of lines = 5
Number of words = 36
/* converting full name to surname with initials */
Number of characters = 205

Fig. 9.13 Counting of characters, words and lines in a text strcpy(name[i], surname[i] );
strcat(name[i], “,”);
dummy[0] = first_name[i][0];
Character Arrays and Strings 279 280 Programming in C

dummy[1] = ‘\0’; Josian Willard Gibbs 123145


strcat(name[i], dummy); CUSTOMERS LIST IN ALPHABETICAL ORDER
strcat(name[i], “.”);
dummy[0] = second_name[i][0]; Argand,J.R 900823
dummy[1] = ‘\0’; Bessel,F.W 719731
strcat(name[i], dummy); Gandhi,M.K 362718
Gauss,C.F 806788
}
Gibbs,J.W 123145
/* Alphabetical ordering of surnames */
Lagrange,J.L 869245
Leibniz,G.W 711518
for(i=1; i <= CUSTOMERS-1; i++)
Poisson,S.D 853240
for(j=1; j <= CUSTOMERS-i; j++) Stokes,G.G 545454
if(strcmp (name[j-1], name[j]) > 0) Sturm,C.F 222031
{
/* Swaping names */ Fig. 9.14 Program to alphabetize a customer list
strcpy(dummy, name[j-1]);
strcpy(name[j-1], name[j]);
strcpy(name[j], dummy); revieW QueStionS
9.1 State whether the following statements are true or false
/* Swaping telephone numbers */ (a) When initializing a string variable during its declaration, we must include the null character
strcpy(dummy, telephone[j-1]); as part of the string constant, like “GOOD\0”. [LO 9.1 M]
strcpy(telephone[j-1],telephone[j]); (b) The gets function automatically appends the null character at the end of the string read
strcpy(telephone[j], dummy); from the keyboard. [LO 9.2 E]
} (c) When reading a string with scanf, it automatically inserts the terminating null character.
/* printing alphabetical list */ [LO 9.2 E]
printf(“\nCUSTOMERS LIST IN ALPHABETICAL ORDER \n\n”); (d) The input function gets has one string parameter. [LO 9.2 E]
for(i=0; i < CUSTOMERS ; i++) (e) The function scanf cannot be used in any way to read a line of text with the white-spaces.
printf(“ %-20s\t %-10s\n”, name[i], telephone[i]); [LO 9.2 M]
} (f) The function getchar skips white-space during input. [LO 9.2 M]
(g) In C, strings cannot be initialized at run time. [LO 9.2 H]
(h) String variables cannot be used with the assignment operator. [LO 9.4 E]
Output
(i) We cannot perform arithmetic operations on character variables. [LO 9.4 E]
Input names and telephone numbers
(j) The ASCII character set consists of 128 distinct characters. [LO 9.4 E]
?Gottfried Wilhelm Leibniz 711518
(k) In the ASCII collating sequence, the uppercase letters precede lowercase letters. [LO 9.4 M]
Joseph Louis Lagrange 869245
(l) In C, it is illegal to mix character data with numeric data in arithmetic operations. [LO 9.4 M]
Jean Robert Argand 900823 (m) The function call strcpy(s2, s1); copies string s2 into string s1. [LO 9.4 M]
Carl Freidrich Gauss 806788 (n) The function call strcmp(“abc”, “ABC”); returns a positive number. [LO 9.4 M]
Simon Denis Poisson 853240 (o) We can assign a character constant or a character variable to an int type variable. [LO 9.4 H]
Friedrich Wilhelm Bessel 719731 9.2 Fill in the blanks in the following statements.
Charles Francois Sturm 222031 (a) We can use the conversion specification _______in scanf to read a line of text. [LO 9.2 E]
George Gabriel Stokes 545454 (b) The function _______does not require any conversion specification to read a string from the
Mohandas Karamchand Gandhi 362718 keyboard. [LO 9.2 E]
User-Defined Functions 299 300 Programming in C

As pointed out earlier, a function that does not return any value cannot be used in an expression. It scanf(“%f”, &inrate);
can only be used as an independent statement.
printf(“Period? “);
scanf(“%d”, &period);
Worked-out proBlem 10.1 E
Write a program with multiple functions that do not communicate any data between them. sum = principal;
year = 1;
A program with three user-defined functions is given in Fig. 10.4. main is the calling function that while(year <= period)
calls printline and value functions. Since both the called functions contain no arguments, there are {
no argument declarations. The printline function, when encountered, prints a line with a length of 35
sum = sum *(1+inrate);
characters as prescribed in the function. The value function calculates the value of principal amount
year = year +1;
after a certain period of years and prints the results. The following equation is evaluated repeatedly:
}
value = principal(1+interest-rate)
printf(“\n%8.2f %5.2f %5d %12.2f\n”,
Program principal,inrate,period,sum);
/* Function declaration */ }
void printline (void);
void value (void); Output
main() — — — — — — — — — — — — — — — — — — — — — — —
{ Principal amount? 5000
printline(); Interest rate? 0.12
value(); Period? 5
printline();
} 5000.00 0.12 5 8811.71
/* Function1: printline( ) */ — — — — — — — — — — — — — — — — — — — — — — —

Fig. 10.4 Functions with no arguments and no return values


void printline(void) /* contains no arguments */
{ It is important to note that the function value receives its data directly from the terminal. The input
int i ; data include principal amount, interest rate and the period for which the final value is to be calculated.
The while loop calculates the final value and the results are printed by the library function printf. When
for(i=1; i <= 35; i++) the closing brace of value( ) is reached, the control is transferred back to the calling function main.
printf(“%c”,’-’); Since everything is done by the value itself there is in fact nothing left to be sent back to the called
printf(“\n”); function. Return types of both printline and value are declared as void.
Note that no return statement is employed. When there is nothing to be returned, the return statement
}
is optional. The closing brace of the function signals the end of execution of the function, thus returning
/* Function2: value( ) */
the control, back to the calling function.
void value(void) /* contains no arguments */
{
int year, period; ARGUMENTS BUT NO RETURN VALUES
float inrate, sum, principal; In Fig. 10.4 the main function has no control over the way the functions receive input data. For example,
the function printline will print the same line each time it is called. Same is the case with the function
printf(“Principal amount?”); value. We could make the calling function to read data from the terminal and pass it on to the called
function. This approach seems to be wiser because the calling function can check for the validity of data,
scanf(“%f”, &principal);
if necessary, before it is handed over to the called function.
printf(“Interest rate? “);
The nature of data communication between the calling function and the called function with arguments
but no return value is shown in Fig. 10.5.

E for Easy, M for Medium and H for High


302 Programming in C User-Defined Functions 303

We should ensure that the function call has matching arguments. In case, the actual arguments }
are more than the formal arguments (m > n), the extra actual arguments are discarded. On the other void printline(char ch)
hand, if the actual arguments are less than the formal arguments, the unmatched formal arguments are
{
initialized to some garbage values. Any mismatch in data type may also result in passing of garbage
values. Remember, no error message will be generated. int i ;
While the formal arguments must be valid variable names, the actual arguments may be variable for(i=1; i <= 52; i++)
names, expressions, or constants. The variables used in actual arguments must be assigned values printf(“%c”,ch);
before the function call is made. printf(“\n”);
Remember that, when a function call is made, only a copy of the values of actual arguments is }
passed into the called function. What occurs inside the function will have no effect on the variables used void value(float p, float r, int n)
in the actual argument list.
{
int year ;
Worked-out proBlem 10.2 M float sum ;
Modify the program of Program 10.1 to include the arguments in the function calls. sum = p ;
year = 1;
The modified program with function arguments is presented in Fig. 10.7. Most of the program is identical
while(year <= n)
to the program in Fig. 10.4. The input prompt and scanf assignment statement have been moved from
{
value function to main. The variables principal, inrate, and period are declared in main because they
are used in main to receive data. The function call sum = sum * (1+r);
value(principal, inrate, period); year = year +1;
passes information it contains to the function value. }
The function header of value has three formal arguments p,r, and n which correspond to the actual printf(“%f\t%f\t%d\t%f\n”,p,r,n,sum);
arguments in the function call, namely, principal, inrate, and period. On execution of the function call, }
the values of the actual arguments are assigned to the corresponding formal arguments. In fact, the
following assignments are accomplished across the function boundaries: Output
p = principal;
r = inrate;
Enter principal amount, interest rate, and period
n = period;
5000 0.12 5
Program ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
/* prototypes */ 5000.000000 0.120000 5 8811.708984
void printline (char c); CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
void value (float, float, int);
Fig. 10.7 Functions with arguments but no return values
main( )
The variables declared inside a function are known as local variables and therefore their values are
{ local to the function and cannot be accessed by any other function. We shall discuss more about this
float principal, inrate; later in the chapter.
int period; The function value calculates the final amount for a given period and prints the results as before.
Control is transferred back on reaching the closing brace of the function. Note that the function does not
printf(“Enter principal amount, interest”); return any value.
printf(“ rate, and period \n”); The function printline is called twice. The first call passes the character ‘Z’, while the second passes
the character ‘C’ to the function. These are assigned to the formal argument ch for printing lines (see
scanf(“%f %f %d”,&principal, &inrate, &period);
the output).
printline(‘Z’);
value(principal,inrate,period);
printline(‘C’);
304 Programming in C User-Defined Functions 305

Variable Number of Arguments Program


Some functions have a variable number of arguments and data types which cannot be known at compile void printline (char ch, int len);
time. The printf and scanf functions are typical examples. The ANSI standard proposes new symbol value (float, float, int);
called the ellipsis to handle such functions. The ellipsis consists of three periods (…) and used as shown
below:
main( )
double area(float d,…)
Both the function declaration and definition should use ellipsis to indicate that the arguments are arbitrary {
both in number and type. float principal, inrate, amount;
int period;
ARGUMENTS WITH RETURN VALUES printf(“Enter principal amount, interest”);
The function value in Fig. 10.7 receives data from the calling function through arguments, but does printf(“rate, and period\n”);
not send back any value. Rather, it displays the results of calculations at the terminal. However, we scanf(%f %f %d”, &principal, &inrate, &period);
may not always wish to have the result of a function displayed. We may use it in the calling function printline (‘*’ , 52);
for further processing. Moreover, to assure a high degree of portability between programs, a function amount = value (principal, inrate, period);
should generally be coded without involving any I/O operations. For example, different programs may
printf(“\n%f\t%f\t%d\t%f\n\n”,principal,
require different output formats for display of results. These shortcomings can be overcome by handing
over the result of a function to its calling function where the returned value can be used as required by inrate,period,amount);
the program. printline(‘=’,52);
A self-contained and independent function should behave like a ‘black box’ that receives a predefined }
form of input and outputs a desired value. Such functions will have two-way data communication as void printline(char ch, int len)
shown in Fig. 10.8. {
int i;
function1 ( ) Values function 2 (f )
for (i=1;i<=len;i++) printf(“%c”,ch);
of arguments
printf(“\n”);
}
function 2 (a)
value(float p, float r, int n) /* default return type */
Function result return (e) {
int year;
float sum;
sum = p; year = 1;
Fig. 10.8 Two-way data communication between functions while(year <=n)
We shall modify the program in Fig. 10.7 to illustrate the use of two-way data communication between {
the calling and the called functions. sum = sum * (l+r);
year = year +1;
Worked-out proBlem 10.3 M }
return(sum); /* returns int part of sum */
In the program presented in Fig. 10.7 modify the function value, to return the final amount calculated
to the main, which will display the required output at the terminal. Also extend the versatility of the }
function printline by having it to take the length of the line as an argument. Output
Enter principal amount, interest rate, and period
The modified program with the proposed changes is presented in Fig. 10.9. One major change is the 5000 0.12 5
movement of the printf statement from value to main.
***************************************************
5000.000000 0.1200000 5 8811.000000
= = = = = = = = = = = = = = = = = = = = = = = = = =
Fig. 10.9 Functions with arguments and return values
306 Programming in C User-Defined Functions 307

The calculated value is passed on to main through statement: Figure 10.10 shows a power function that returns a double. The prototype declaration
return(sum); double power(int, int);
Since, by default, the return type of value function is int, the ‘integer’ value of sum at this point is appears in main, before power is called.
returned to main and assigned to the variable amount by the functional call
amount = value (principal, inrate, period); Program
The following events occur, in order, when the above function call is executed:
main( )
1. The function call transfers the control along with copies of the values of the actual arguments {
to the function value where the formal arguments p, r, and n are assigned the actual values of
int x,y; /*input data */
principal, inrate and period respectively.
double power(int, int); /* prototype declaration*/
2. The called function value is executed line by line in a normal fashion until the return(sum);
printf(“Enter x,y:”);
statement is encountered. At this point, the integer value of sum is passed back to the function-
call in the main and the following indirect assignment occurs: scanf(“%d %d” , &x,&y);
value(principal, inrate, period) = sum; printf(“%d to power %d is %f\n”, x,y,power (x,y));
3. The calling statement is executed normally and the returned value is thus assigned to amount, a }
float variable. double power (int x, int y);
4. Since amount is a float variable, the returned integer part of sum is converted to floating-point {
value. See the output. double p;
Another important change is the inclusion of second argument to printline function to receive the p = 1.0 ; /* x to power zero */
value of length of the line from the calling function. Thus, the function call
printline(‘*’, 52); if(y >=0)
will transfer the control to the function printline and assign the following values to the formal arguments
while(y— –) /* computes positive powers */
ch, and len:
p *= x;
ch = ‘*’ ;
else
len = 52;
while (y++) /* computes negative powers */
p /= x;
returning Float values return(p); /* returns double type */
We mentioned earlier that a C function returns a value of the type int as the default case when no other
type is specified explicitly. For example, the function value of Program 10.3 does all calculations using }
floats but the return statement Output
return(sum);
returns only the integer part of sum. This is due to the absence of the type-specifier in the function
Enter x,y:16 2
header. In this case, we can accept the integer value of sum because the truncated decimal part is
insignificant compared to the integer part. However, there will be times when we may find it necessary 16 to power 2 is 256.000000
to receive the float or double type of data. For example, a function that calculates the mean or standard
deviation of a set of values should return the function value in either float or double. Enter x,y:16 -2
In all such cases, we must explicitly specify the return type in both the function definition and the 16 to power -2 is 0.003906
prototype declaration.
If we have a mismatch between the type of data that the called function returns and the type of data Fig. 10.10 Power functions: Illustration of return of float values
that the calling function expects, we will have unpredictable results. We must, therefore, be very careful
to make sure that both types are compatible.
Worked-out proBlem 10.5 H
Worked-out proBlem 10.4 E The program in Fig. 10.11 shows how to write a C program (float x [ ], int n) that returns the position
of the first minimum value among the first n elements of the given array x.
Write a function power that computes x raised to the power y for integers x and y and returns double-
type value.
308 Programming in C 314 Programming in C

Program Passing addresses of parameters to the functions is referred to as pass by address (or pass by
#include <stdio.h> pointers). Note that we cannot pass a whole array by value as we did in the case of ordinary variables.
#include <conio.h>
#include <stdio.h> Worked-out proBlem 10.6 H
Write a program to calculate the standard deviation of an array of values. The array elements are
int minpos(float []. int); read from the terminal. Use functions to calculate standard deviation and mean.
void main()
{ Standard deviation of a set of n values is give by
int n: n
1
float x[10] = {12.5, 3.0, 45.1, 8.2, 19.3, 10.0, 7.8, 23.7, 29.9, 5.2}; S.D =
n Â(x - x )
i =1
i
2

printf(“Enter the value of n: “);


scanf(“%d”, &n); Where x is the mean of the values.

Program
if(n>=1 && n<=10) #include <math.h>
: #define SIZE 5
else float std_dev(float a[], int n);
{ float mean (float a[], int n);
printf(“invalid value of n...Press any key to terminate the program..“); main( )
getch(): {
exit(0); float value[SIZE];
} int i;
printf(“Within the first %d elements of array, the first minimum value is
stored at index %d”. n, minpos(x,n)); printf(“Enter %d float values\n”, SIZE);
getch(); for (i=0 ;i < SIZE ; i++)
} scanf(“%f”, &value[i]);
int minpos(float a[]).int N) printf(“Std.deviation is %f\n”, std_dev(value,SIZE));
{ }
int i.index; float std_dev(float a[], int n)
float min-9999.99: {
int i;
for(i=0;i<N;i++)
float x, sum = 0.0;
if(a[i]<min)
x = mean (a,n);
{
for(i=0; i < n; i++)
min-a[i];
sum += (x-a[i])*(x-a[i]);
index = i; return(sqrt(sum/(float)n));
} }
return (index); float mean(float a[],int n)
} {
int i ;
Output
float sum = 0.0;
Enter the value of n: 5
for(i=0 ; i < n ; i++)
Within the first 5 elements of array, the first minimum value is stored at index 1 sum = sum + a[i];
return(sum/(float)n);
Fig. 10.11 Program to return the position of the first minimum value in an array
}
User-Defined Functions 315 316 Programming in C

Output printf(“Marks after sorting\n”);


Enter 5 float values for(i = 0; i < 5; i++)
35.0 67.0 79.5 14.20 55.75 printf(“%4d”, marks[i]);
printf(“\n”);
Std.deviation is 23.231582
}
Fig. 10.12 Passing of arrays to a function void sort(int m, int x[ ])
A multifunction program consisting of main, std_dev, and mean functions is shown in Fig. 10.12. {
main reads the elements of the array value from the terminal and calls the function std_dev to print the int i, j, t;
standard deviation of the array elements. Std_dev, in turn, calls another function mean to supply the
average value of the array elements.
for(i = 1; i <= m-1; i++)
Both std_dev and mean are defined as floats and therefore they are declared as floats in the global
section of the program. for(j = 1; j <= m-i; j++)
if(x[j-1] >= x[j])
Three Rules to Pass an Array to a Function
1. The function must be called by passing only the name of the array. {
2. In the function definition, the formal parameter must be an array type; the size of the array does not t = x[j-1];
need to be specified. x[j-1] = x[j];
3. The function prototype must show that the argument is an array. x[j] = t;
When dealing with array arguments, we should remember one major distinction. If a function changes }
the values of the elements of an array, then these changes will be made to the original array that passed
}
to the function. When an entire array is passed as an argument, the contents of the array are not copied
Output
into the formal parameter array; instead, information about the addresses of array elements are passed
on to the function. Therefore, any changes introduced to the array elements are truly reflected in the Marks before sorting
original array in the calling function. However, this does not apply when an individual element is passed 40 90 73 81 35
on as argument. Program 10.6 highlights these concepts.
Marks after sorting
35 40 73 81 90
Worked-out proBlem 10.7 M
Fig. 10.13 Sorting of array elements using a function
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. 10.13. Its output clearly
shows that a function can change the values in an array passed as an argument.
two-dimensional Arrays
Like simple arrays, we can also pass multi-dimensional arrays to functions. The approach is similar to
Program
the one we did with one-dimensional arrays. The rules are simple.
void sort(int m, int x[ ]);
main() 1. The function must be called by passing only the array name.
{ 2. In the function definition, we must indicate that the array has two-dimensions by including two
int i; sets of brackets.
3. The size of the second dimension must be specified.
int marks[5] = {40, 90, 73, 81, 35};
4. The prototype declaration should be similar to the function header.
The function given below calculates the average of the values in a two-dimensional matrix.
printf(“Marks before sorting\n”);
for(i = 0; i < 5; i++) double average(int x[][N], int M, int N)
printf(“%d “, marks[i]); {
printf(“\n\n”); int i, j;
double sum = 0.0;
sort (5, marks); for (i=0; i<M; i++)
User-Defined Functions 319 320 Programming in C

main( )
int m = 10;
{
printf(“%d\n”,m); /* First output */
int number;
}
– – –– –
– – –– –
void function2(void)
}
{
We may also use the keyword auto to declare automatic variables explicitly.
int m = 100;
main( )
function1();
{
printf(“%d\n”,m); /* Second output */
auto int number;
}
– – –– –
– – –– –
Output
}
10
One important feature of automatic variables is that their value cannot be changed accidentally by
what happens in some other function in the program. This assures that we may declare and use the 100
same variable name in different functions in the same program without causing any confusion to the 1000
compiler.
Fig. 10.14 Working of automatic variables

M There are two consequences of the scope and longevity of auto variables worth remembering. First,
Worked-out proBlem 10.8 any variable local to main will be normally alive throughout the whole program, although it is active only
Write a multifunction to illustrate how automatic variables work. in main. Secondly, during recursion, the nested variables are unique auto variables, a situation similar
to function-nested auto variables with identical names.
A program with two subprograms function1 and function2 is shown in Fig. 10.14. m is an automatic
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. external variables
When executed, main calls function2 which in turn calls function1. When main is active, m = 1000; Variables that are both alive and active throughout the entire program are known as external variables.
but when function2 is called, the main’s m is temporarily put on the shelf and the new local m = 100 They are also known as global variables. Unlike local variables, global variables can be accessed
becomes active. Similarly, when function1 is called, both the previous values of m are put on the shelf by any function in the program. External variables are declared outside a function. For example, the
and the latest value of m (=10) becomes active. As soon as function1 (m=10) is finished, function2 external declaration of integer number and float length might appear as:
(m=100) takes over again. As soon it is done, main (m=1000) takes over. The output clearly shows that
int number;
the value assigned to m in one function does not affect its value in the other functions; and the local
float length = 7.5;
value of m is destroyed when it leaves a function.
main( )
Program {
– – –– –– –
void function1(void);
– – –– –– –
void function2(void);
}
main( ) function1( )
{ {
int m = 1000; – – –– –– –
function2(); – – –– –– –
}
printf(“%d\n”,m); /* Third output */ function2( )
{
}
– – –– –– –
void function1(void)
– – –– –– –
{ }
User-Defined Functions 321 322 Programming in C

The variables number and length are available for use in all the three functions. In case a local fun1(void)
variable and a global variable have the same name, the local variable will have precedence over the {
global one in the function where it is declared. Consider the following example:
x = x + 10 ;
int count;
}
main( )
int fun2(void)
{
{
count = 10;
int x ; /* local */
– – –– –
x = 1 ;
– – –– –
return (x);
}
}
function( )
fun3(void)
{
{
int count = 0;
x = x + 10 ; /* global x */
– – –– –
}
– – –– –
count = count+1;
Output
}
x = 10
When the function references the variable count, it will be referencing only its local variable, not the
x = 20
global one. The value of count in main will not be affected.
x = 1
x = 30
Worked-out proBlem 10.9 E
Fig. 10.15 Illustration of properties of global variables
Write a multifunction program to illustrate the properties of global variables.
Once a variable has been declared as global, any function can use it and change its value. Then,
A program to illustrate the properties of global variables is presented in Fig. 10.15. Note that variable
subsequent functions can reference only that new value.
x is used in all functions but none except fun2, has a definition for x. Because x has been declared
‘above’ all the functions, it is available to each function without having to pass x as a function argument. Global Variables as Parameters
Further, since the value of x is directly available, we need not use return(x) statements in fun1 and Since all functions in a program source file can access global variables, they can be used for passing
fun3. However, since fun2 has a definition of x, it returns its local value of x and therefore uses a return values between the functions. However, using global variables as parameters for passing values poses
statement. In fun2, the global x is not visible. The local x hides its visibility here. certain problems.

Program ∑ The values of global variables which are sent to the called function may be changed inadvertently
by the called function.
int fun1(void);
∑ Functions are supposed to be independent and isolated modules. This character is lost, if they
int fun2(void);
use global variables.
int fun3(void);
∑ It is not immediately apparent to the reader which values are being sent to the called function.
int x ; /* global */
∑ A function that uses global variables suffers from reusability.
main( )
One other aspect of a global variable is that it is available only from the point of declaration to the end
{ of the program. Consider a program segment as shown below:
x = 10 ; /* global x */
main( )
printf(“x = %d\n”, x);
{
printf(“x = %d\n”, fun1());
y = 5;
printf(“x = %d\n”, fun2());
. . . .
printf(“x = %d\n”, fun3());
. . . .
}
}
User-Defined Functions 325 User-Defined Functions 331

remainder of the program. Therefore, internal static variables can be used to retain values between ∑ Static variables are initialized at compile time and therefore, they are initialized only once. [LO 10.6]
function calls. For example, it can be used to count the number of calls made to a function. ∑ Avoid the use of names that hide names in outer scope. [LO 10.6]

Worked-out proBlem 10.10 E BrieF CASeS


Write a program to illustrate the properties of a static variable.
1. Calculation of Area under a Curve [LO 10.1, 10.2, 10.3, 10.6 M]
The program in Fig. 10.16 explains the behaviour of a static variable.
One of the applications of computers in numerical analysis is computing the area under a curve. One
Program simple method of calculating the area under a curve is to divide the area into a number of trapezoids of
void stat(void); same width and summing up the area of individual trapezoids. The area of a trapezoid is given by
main ( ) Area = 0.5 * (h1 + h2) * b
{ where h1 and h2 are the heights of two sides and b is the width as shown in Fig. 10.19.
int i; The program in Fig. 10.21 calculates the area for a curve of the function
for(i=1; i<=3; i++) f(x) = x2 + 1
stat( ); between any two given limits, say, A and B.
} Input
void stat(void) Lower limit (A)
{ Upper limit (B)
static int x = 0; Number of trapezoids

x = x+1;
Curve
printf(“x = %d\n”, x);
}
Output
x = 1 b
f(x)
x = 2 h1 h2
x = 3

Fig. 10.16 Illustration of static variable

A static variable is initialized only once, when the program is compiled. It is never initialized again.
During the first call to stat, x is incremented to 1. Because x is static, this value persists and therefore,
the next call adds another 1 to x giving it a value of 2. The value of x becomes three when the third call A x B
is made. Fig. 10.19 Area under a curve
Had we declared x as an auto variable, the output would have been:
x=1 Output
x=1 Total area under the curve between the given limits.
x=1
This is because each time stat is called, the auto variable x is initialized to zero. When the function Algorithm
terminates, its value of 1 is lost. 1. Input the lower and upper limits and the number of trapezoids.
An external static variable is declared outside of all functions and is available to all the functions in 2. Calculate the width of trapezoids.
that program. The difference between a static external variable and a simple external variable is that 3. Initialize the total area.
the static external variable is available only within the file where it is defined while the simple external 4. Calculate the area of trapezoid and add to the total area.
variable can be accessed by other files. 5. Repeat step-4 until all the trapezoids are completed.
6. Print total area.
332 Programming in C User-Defined Functions 333

The algorithm is implemented in top-down modular form as in Fig. 10.20. float find_area(float a, float b, int n)
main {
float base, lower, h1, h2; /* LOCAL VARIABLES */
float function_x(float x); /* prototype */
input find_area float trap_area(float h1,float h2,float base);/*prototype*/
base = (b-1)/n;
lower = a;
for(lower =a; lower <= b-base; lower = lower + base)
function_x trap_area
{
Fig. 10.20 Modular chart h1 = function_x(lower);
h1 = function_x(lower + base);
The evaluation of f(x) has been done using a separate function so that it can be easily modified to
allow other functions to be evaluated. total_area += trap_area(h1, h2, base);
The output for two runs shows that better accuracy is achieved with larger number of trapezoids. The }
actual area for the limits 0 and 3 is 12 units (by analytical method). return(total_area);
float trap_area(float height_1,float height_2,float base)
Program
{
#include <stdio.h>
float area; /* LOCAL VARIABLE */
float start_point, /* GLOBAL VARIABLES */ * *
area = 0.5 (height_1 + height_2) base;
end_point,
return(area);
total_area;
}
int numtraps;
main( ) float function_x(float x)
{ {
void input(void); /* F(X) = X * X + 1 */
float find_area(float a,float b,int n); /* prototype */ return(x*x + 1);
}
print(“AREA UNDER A CURVE”); Output
input( ); AREA UNDER A CURVE
Enter lower limit: 0
total_area = find_area(start_point, end_point, numtraps);
Enter upper limit: 3
printf(“TOTAL AREA = %f”, total_area);
Enter number of trapezoids: 30
}
TOTAL AREA = 12.005000
void input(void)
{
AREA UNDER A CURVE
printf(“\n Enter lower limit:”); Enter lower limit: 0
scanf(“%f”, &start_point); Enter upper limit: 3
printf(“Enter upper limit:”); Enter number of trapezoids: 100
scanf(“%f”, &end_point); TOTAL AREA = 12.000438
printf(“Enter number of trapezoids:”); Fig. 10.21 Computing area under a curve
scanf(“%d”, &numtraps);
}
Pointers 343 344 Programming in C

ACCESSING ThE ADDRESS OF A VARIABLE Output


Lo 11.1 The actual location of a variable in the memory is system dependent and
Know the concept therefore, the address of a variable is not known to us immediately. How can we A is stored at addr 4436.
of pointers then determine the address of a variable? This can be done with the help of the 125 is stored at addr 4434.
operator & available in C. We have already seen the use of this address operator
10.250000 is stored at addr 4442.
in the scanf function. The operator & immediately preceding a variable returns the
18.760000 is stored at addr 4438.
address of the variable associated with it. For example, the statement
p = &quantity; Fig. 11.4 Accessing the address of a variable
would assign the address 5000 (the location of quantity) to the variable p. The & operator can be
remembered as ‘address of ’.
The & operator can be used only with a simple variable or an array element. The following are illegal DECLARING POINTER VARIABLES Lo 11.2
use of address operator: In C, every variable must be declared for its type. Since pointer variables Determine how
1. &125 (pointing at constants). contain addresses that belong to a separate data type, they must be declared pointer variables are
2. int x[10]; as pointers before we use them. The declaration of a pointer variable takes used in a program
&x (pointing at array names). the following form:
3. &(x+y) (pointing at expressions). data_type *pt_name;
If x is an array, then expressions such as This tells the compiler three things about the variable pt_name.
&x[0] and &x[i+3] 1. The asterisk (*) tells that the variable pt_name is a pointer variable.
are valid and represent the addresses of 0th and (i+3)th elements of x. 2. pt_name needs a memory location.
3. pt_name points to a variable of type data_type.
e For example,
WorKeD-out ProbLeM 11.1
int *p; /* integer pointer */
Write a program to print the address of a variable along with its value. declares the variable p as a pointer variable that points to an integer data type. Remember that the
type int refers to the data type of the variable being pointed to by p and not the type of the value of the
The program shown in Fig. 11.4, declares and initializes four variables and then prints out these values
pointer. Similarly, the statement
with their respective storage locations. Note that we have used %u format for printing address values.
Memory addresses are unsigned integers. float *x; / * float pointer */
declares x as a pointer to a floating-point variable.
Program
The declarations cause the compiler to allocate memory locations for the pointer variables p and
main()
x. Since the memory locations have not been assigned any values, these locations may contain some
{ unknown values in them and therefore they point to unknown locations as shown:
char a; int *p;
P ? ?
int x;
float p, q;
contains points to
grabage unknown location
a = ‘A’;
x = 125; pointer Declaration style
p = 10.25, q = 18.76;
Pointer variables are declared similarly as normal variables except for the addition of the unary * operator.
printf(“%c is stored at addr %u.\n”, a, &a); This symbol can appear anywhere between the type name and the printer variable name. Programmers
printf(“%d is stored at addr %u.\n”, x, &x); use the following styles:
printf(“%f is stored at addr %u.\n”, p, &p); int* p; /* style 1 */
printf(“%f is stored at addr %u.\n”, q, &q); int *p; /* style 2 */
int * p; /* style 3 */
} However, the style 2 is becoming increasingly popular due to the following reasons:
1. This style is convenient to have multiple declarations in the same statement. Example:
int *p, x, *q;
E for Easy, M for Medium and H for High
Pointers 347 350 Programming in C

n = quantity;
In C, the assignment of pointers and addresses is always done symbolically, by means of symbolic WorKeD-out ProbLeM 11.3 M
names. You cannot access the value stored at the address 5368 by writing *5368. It will not work.
Write a program to illustrate the use of pointers in arithmetic operations.
Program 11.2 illustrates the distinction between pointer value and the value it points to.
The program in Fig.11.7 shows how the pointer variables can be directly used in expressions. It also
e illustrates the order of evaluation of expressions. For example, the expression
WorKeD-out ProbLeM 11.2 4* – *p2 / *p1 + 10
Write a program to illustrate the use of indirection operator ‘*’ to access the value pointed to by a is evaluated as follows:
pointer. ((4 * (–(*p2))) / (*p1)) + 10
The program and output are shown in Fig.11.5. The program clearly shows how we can access the When *p1 = 12 and *p2 = 4, this expression evaluates to 9. Remember, since all the variables are of
value of a variable using a pointer. You may notice that the value of the pointer ptr is 4104 and the value type int, the entire evaluation is carried out using the integer arithmetic.
it points to is 10. Further, you may also note the following equivalences: Program
x = *(&x) = *ptr = y main()
&x = &*ptr {
Program int a, b, *p1, *p2, x, y, z;
main() a = 12;
{ b = 4;
int x, y; p1 = &a;
int *ptr; p2 = &b;
x = 10; x = *p1 * *p2 – 6;
ptr = &x; y = 4* – *p2 / *p1 + 10;
y = *ptr; printf(“Address of a = %u\n”, p1);
printf(“Value of x is %d\n\n”,x); printf(“Address of b = %u\n”, p2);
printf(“%d is stored at addr %u\n”, x, &x); printf(“\n”);
printf(“%d is stored at addr %u\n”, *&x, &x); printf(“a = %d, b = %d\n”, a, b);
printf(“%d is stored at addr %u\n”, *ptr, ptr); printf(“x = %d, y = %d\n”, x, y);
printf(“%d is stored at addr %u\n”, ptr, &ptr); *p2 = *p2 + 3;
printf(“%d is stored at addr %u\n”, y, &y); *p1 = *p2 – 5;
*ptr = 25; z = *p1 * *p2 – 6;
printf(“\nNow x = %d\n”,x); printf(“\na = %d, b = %d,”, a, b);
printf(“ z = %d\n”, z);
} }
Output
Output
Value of x is 10
Address of a = 4020
10 is stored at addr 4104
Address of b = 4016
10 is stored at addr 4104 a = 12, b = 4
10 is stored at addr 4104 x = 42, y = 9
4104 is stored at addr 4106 a = 2, b = 7, z = 8
10 is stored at addr 4108
Fig. 11.7 Evaluation of pointer expressions
Now x = 25

Fig. 11.5 Accessing a variable through its pointer


352 Programming in C Pointers 353

Suppose the base address of x is 1000 and assuming that each integer requires two bytes, the five i = 0;
elements will be stored as follows:
p = x; /* initializing with base address of x */
Elements x[0] x[1] x[2] x[3] x[4]
printf(“Element Value Address\n\n”);
Value 1 2 3 4 5 while(i < 5)
{
Address 1000 1002 1004 1006 1008
printf(“ x[%d] %d %u\n”, i, *p, p);
Base address sum = sum + *p; /* accessing array element */
i++, p++; /* incrementing pointer */
The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the value
}
of x is 1000, the location where x[0] is stored. That is,
printf(“\n Sum = %d\n”, sum);
x = &x[0] = 1000
If we declare p as an integer pointer, then we can make the pointer p to point to the array x by the printf(“\n &x[0] = %u\n”, &x[0]);
following assignment: printf(“\n p = %u\n”, p);
p = x; }
This is equivalent to
p = &x[0]; Output
Now, we can access every value of x using p++ to move from one element to another. The relationship Element Value Address
between p and x is shown as: x[0] 5 166
p = &x[0] (= 1000)
x[1] 9 168
p+1 = &x[1] (= 1002)
x[2] 6 170
p+2 = &x[2] (= 1004)
p+3 = &x[3] (= 1006) x[3] 3 172
p+4 = &x[4] (= 1008) x[4] 7 174
You may notice that the address of an element is calculated using its index and the scale factor of Sum = 55
the data type. For instance, &x[0] = 166
address of x[3] = base address + (3 x scale factor of int) p = 176
= 1000 + (3 x 2) = 1006 Fig. 11.8 Accessing one-dimensional array elements using the pointer
When handling arrays, instead of using array indexing, we can use pointers to access array
elements. Note that *(p+3) gives the value of x[3]. The pointer accessing method is much faster than It is possible to avoid the loop control variable i as shown:
array indexing. .....
The Worked-Out Problem 11.4 illustrates the use of pointer accessing method. p = x;
while(p <= &x[4])
WorKeD-out ProbLeM 11.4 M {
sum += *p;
Write a program using pointers to compute the sum of all elements stored in an array.
p++;
The program shown in Fig. 11.8 illustrates how a pointer can be used to traverse an array element. }
Since incrementing an array pointer causes it to point to the next element, we need only to add one to .....
p each time we go through the loop. Here, we compare the pointer p with the address of the last element to determine when the array
has been traversed.
Program Pointers can be used to manipulate two-dimensional arrays as well. We know that in a one-
main() dimensional array x, the expression
{ *(x+i) or *(p+i)
int *p, sum, i; represents the element x[i]. Similarly, an element in a two-dimensional array can be represented by the
pointer expression as follows:
int x[5] = {5,9,6,3,7};
*(*(a+i)+j) or *(*(p+i)j)
Pointers 355 356 Programming in C

POINTERS AND ChARACTER STRINGS D E L H I \0


We have seen in Chapter 8 that strings are treated like character arrays and therefore, they are declared
and initialized as follows:
char str [5] = “good”;
The compiler automatically inserts the null character ‘\0’ at the end of the string. C supports an name cptr
alternative method to create strings using pointer variables of type char. Example: (5 4) (5 9)

char *str = “good”; The output also shows the address location of each character. Note that each character occupies
This creates a string for the literal and then stores its address in the pointer variable str. one memory cell (byte).
The pointer str now points to the first character of the string “good” as:
Program
g o o d \0
main()
{
char *name;
int length;
str char *cptr = name;
name = “DELHI”;
We can also use the run-time assignment for giving values to a string pointer. Example
printf (“%s\n”, name);
char * string1;
while(*cptr != ‘\0’)
string1 = “good”;
Note that the assignment {
string1 = “good”; printf(“%c is stored at address %u\n”, *cptr, cptr);
is not a string copy, because the variable string1 is a pointer, not a string. cptr++;
(As pointed out in Chapter 8, C does not support copying one string to another through the assignment }
operation.) length = cptr - name;
We can print the content of the string string1 using either printf or puts functions as follows: printf(“\nLength of the string = %d\n”, length);
printf(“%s”, string1); }
puts (string1);
Remember, although string1 is a pointer to the string, it is also the name of the string. Therefore, we Output
do not need to use indirection operator * here.
DELHI
Like in one-dimensional arrays, we can use a pointer to access the individual characters in a string.
D is stored at address 54
This is illustrated by the Worked-Out Problem 11.5.
E is stored at address 55
L is stored at address 56
WorKeD-out ProbLeM 11.5 e H is stored at address 57
Write a program using pointers to determine the length of a character string. I is stored at address 58

A program to count the length of a string is shown in Fig.11.10. The statement Length of the string = 5
char *cptr = name;
declares cptr as a pointer to a character and assigns the address of the first character of name as Fig. 11.10 String handling by pointers
the initial value. Since a string is always terminated by the null character, the statement
In C, a constant character string always represents a pointer to that string. And therefore the following
while(*cptr != ‘\0’)
statements are valid:
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, char *name;
the statement name = “Delhi”;
length = cptr – name;
gives the length of the string name.
358 Programming in C Pointers 359

Remember the difference between the notations *p[3] and (*p)[3]. Since * has a lower precedence The program in Fig. 11.11 shows how the contents of two locations can be exchanged using their
than [ ], *p[3] declares p as an array of 3 pointers while (*p)[3] declares p as a pointer to an array of address locations. The function exchange() receives the addresses of the variables x and y and
three elements. exchanges their contents.
Program
POINTERS AS FUNCTION ARGUMENTS void exchange (int *, int *); /* prototype */
We have seen earlier that when an array is passed to a function as an main()
Lo 11.6
argument, only the address of the first element of the array is passed, but {
explain how pointers
not the actual values of the array elements. If x is an array, when we call int x, y;
are used with functions
sort(x), the address of x[0] is passed to the function sort. The function uses
and structures x = 100;
this address for manipulating the array elements. Similarly, we can pass the
y = 200;
address of a variable as an argument to a function in the normal fashion. We
used this method when discussing functions that return multiple values (see Chapter 9). printf(“Before exchange : x = %d y = %d\n\n”, x, y);
When we pass addresses to a function, the parameters receiving the addresses should be pointers. exchange(&x,&y); /* call */
The process of calling a function using pointers to pass the addresses of variables is known as ‘call by printf(“After exchange : x = %d y = %d\n\n”, x, y);
reference’. (You know, the process of passing the actual value of variables is known as “call by value”.) }
The function which is called by ‘reference’ can change the value of the variable used in the call. exchange (int *a, int *b)
Consider the following code: {
main() int t;
{
t = *a; /* Assign the value at address a to t */
int x;
*a = *b; /* put b into a */
x = 20;
*b = t; /* put t into b */
change(&x); /* call by reference or address */
}
printf(“%d\n”,x);
}
Output
change(int *p)
{ Before exchange : x = 100 y = 200
*p = *p + 10;
After exchange : x = 200 y = 100
}
When the function change( ) is called, the address of the variable x, not its value, is passed into Fig. 11.11 Passing of pointers as function parameters
the function change(). Inside change( ), the variable p is declared as a pointer and therefore p is the
address of the variable x. The statement, You may note the following points:
*p = *p + 10; 1. The function parameters are declared as pointers.
means ‘add 10 to the value stored at the address p’. Since p represents the address of x, the value of x 2. The dereferenced pointers are used in the function body.
is changed from 20 to 30. Therefore, the output of the program will be 30, not 20.
3. When the function is called, the addresses are passed as actual arguments.
Thus, call by reference provides a mechanism by which the function can change the stored values in
the calling function. Note that this mechanism is also known as “call by address” or “pass by pointers”. The use of pointers to access array elements is very common in C. We have used a pointer to
traverse array elements in Program 11.4. We can also use this technique in designing user-defined
Note C99 adds a new qualifier restrict to the pointers passed as function parameters. See functions discussed in Chapter 9. Let us consider the problem sorting an array of integers discussed in
the Appendix “C99 Features”. Program 9.6.
The function sort may be written using pointers (instead of array indexing) as shown:
void sort (int m, int *x)
M { int i j, temp;
WorKeD-out ProbLeM 11.6 for (i=1; i<= m–1; i++)
Write a function using pointers to exchange the values stored in two locations in the for (j=1; j<= m–1; j++)
memory.
if (*(x+j–1) >= *(x+j))
{
360 Programming in C Pointers 361

temp = *(x+j– 1); int x=0;


*(x+j–1) = *(x+j); int y=20;
*(x+j) = temp; clrstr();
} printf(“\nValue of X and Y before swapping are X=%d and Y=%d”, x,y);
} swap(&x, &y);
Note that we have used the pointer x (instead of array x[ ]) to receive the address of array passed
printf(“\n\nValue of X and Y after swapping are X=%d and Y=%d”, x,y);
and therefore the pointer x can be used to access the array elements (as pointed out in Section 11.10).
getch();
This function can be used to sort an array of integers as follows:
}
. . . . .
int score[4] = {45, 90, 71, 83}; void swap(int *p, int *q)//Value of x and y are transferred using call by
reference
. . . . .
sort(4, score); /* Function call */ {
. . . . . int r;
The calling function must use the following prototype declaration. r=*p;
void sort (int, int *); *p=*q;
This tells the compiler that the formal argument that receives the array is a pointer, not array *q=r;
variable. }
Pointer parameters are commonly employed in string functions. Consider the function copy which Output
copies one string to another.
Value of X and Y before swapping are X=10 and Y=20
copy(char *s1, char *s2)
Value of X and Y after swapping are X=20 and Y=10
{
while( (*s1++ = *s2++) != ‘\0’) Fig. 11.12 Program to pass the arguments using call by reference method
;
} FUNCTIONS RETURNING POINTERS
This copies the contents of s2 into the string s1. Parameters s1 and s2 are the pointers to character We have seen so far that a function can return a single value by its name or return multiple values
strings, whose initial values are passed from the calling function. For example, the calling statement through pointer parameters. Since pointers are a data type in C, we can also force a function to return a
copy(name1, name2); pointer to the calling function. Consider the following code:
will assign the address of the first element of name1 to s1 and the address of the first element of name2 int *larger (int *, int *); /* prototype */
to s2.
main ( )
Note that the value of *s2++ is the character that s2 pointed to before s2 was incremented. Due to the
{
postfix ++, s2 is incremented only after the current value has been fetched. Similarly, s1 is incremented
only after the assignment has been completed. int a = 10;
Each character, after it has been copied, is compared with ‘\0’ and therefore, copying is terminated int b = 20;
as soon as the ‘\0’ is copied. int *p;
p = larger(&a, &b); /Function call */
M printf (“%d”, *p);
WorKeD-out ProbLeM 11.7 }
The program of Fig. 11.12 shows how to calculate the sum of two numbers which are passed as int *larger (int *x, int *y)
arguments using the call by reference method.
{
if (*x>*y)
Program
return (x); / *address of a */
#include<stdio.h>
else
#include<conio.h>
return (y); /* address of b */
void swap (int *p, *q);
}
main()
{
362 Programming in C Pointers 363

The function larger receives the addresses of the variables a and b, decides which one is larger passes a pointer to cos as its first parameter and therefore, the function table evaluates the value of
using the pointers x and y and then returns the address of its location. The returned value is then cos over the range 0.0 to PI at the intervals of 0.5.
assigned to the pointer variable p in the calling function. In this case, the address of b is returned and
assigned to p and therefore the output will be the value of b, namely, 20. Program
Note that the address returned must be the address of a variable in the calling function. It is an error #include <math.h>
to return a pointer to a local variable in the called function. #define PI 3.1415926
double y(double);
POINTERS TO FUNCTIONS double cos(double);
A function, like a variable, has a type and an address location in the memory. It is therefore, possible to double table (double(*f)(), double, double, double);
declare a pointer to a function, which can then be used as an argument in another function. A pointer to
a function is declared as follows: main()
type (*fptr) (); { printf(“Table of y(x) = 2*x*x–x+1\n\n”);
This tells the compiler that fptr is a pointer to a function, which returns type value. The parentheses table(y, 0.0, 2.0, 0.5);
around *fptr are necessary. Remember that a statement like printf(“\nTable of cos(x)\n\n”);
type *gptr(); table(cos, 0.0, PI, 0.5);
would declare gptr as a function returning a pointer to type. }
We can make a function pointer to point to a specific function by simply assigning the name of the double table(double(*f)(),double min, double max, double step)
function to the pointer. For example, the statements { double a, value;
double mul(int, int); for(a = min; a <= max; a += step)
double (*p1)(); {
p1 = mul; value = (*f)(a);
declare p1 as a pointer to a function and mul as a function and then make p1 to point to the function printf(“%5.2f %10.4f\n”, a, value);
mul. To call the function mul, we may now use the pointer p1 with the list of parameters. That is, }
(*p1)(x,y) /* Function call */ }
is equivalent to
double y(double x)
mul(x,y)
{
Note the parentheses around *p1.
return(2*x*x-x+1);
}
WorKeD-out ProbLeM 11.8 H
Write a program that uses a function pointer as a function argument. Output
Table of y(x) = 2*x*x-x+1
A program to print the function values over a given range of values is shown in Fig. 11.13. The printing 0.00 1.0000
is done by the function table by evaluating the function passed to it by the main. 0.50 1.0000
With table, we declare the parameter f as a pointer to a function as follows: 1.00 2.0000
double (*f)(); 1.50 4.0000
The value returned by the function is of type double. When table is called in the statement 2.00 7.0000
table (y, 0.0, 2, 0.5); Table of cos(x)
we pass a pointer to the function y as the first parameter of table. Note that y is not followed by a 0.00 1.0000
parameter list. 0.50 0.8776
During the execution of table, the statement 1.00 0.5403
value = (*f)(a); 1.50 0.0707
calls the function y which is pointed to by f, passing it the parameter a. Thus the function y is evaluated 2.00 -0.4161
over the range 0.0 to 2.0 at the intervals of 0.5. 2.50 -0.8011
Similarly, the call 3.00 -0.9900
table (cos, 0.0, PI, 0.5); Fig. 11.13 Use of pointers to functions
Pointers 365 366 Programming in C

We could also use the notation


Electric_iron 12 350
(*ptr).number
Two_in_one 7 1250
to access the member number. The parentheses around *ptr are necessary because the member
operator ‘.’ has a higher precedence than the operator *.
OUTPUT
Washing machine 5 7500.00
WorKeD-out ProbLeM 11.9 H Electric_iron 12 350.00
Write a program to illustrate the use of structure pointers. Two_in_one 7 1250.00
Fig. 11.14 Pointer to structure variables
A program to illustrate the use of a structure pointer to manipulate the elements of an array of structures
is shown in Fig. 11.14. The program highlights all the features discussed above. Note that the pointer While using structure pointers, we should take care of the precedence of operators.
ptr (of type struct invent) is also used as the loop control index in for loops. The operators ‘–>’ and ‘.’, and () and [] enjoy the highest priority among the operators. They bind very
tightly with their operands. For example, given the definition
Program struct
struct invent {
{ int count;
char *name[20]; float *p; /* pointer inside the struct */
int number; } ptr; /* struct type pointer */
then the statement
float price;
++ptr–>count;
};
increments count, not ptr. However,
main()
(++ptr)–>count;
{ increments ptr first, and then links count. The statement
struct invent product[3], *ptr; ptr++ –> count;
printf(“INPUT\n\n”); is legal and increments ptr after accessing count.
for(ptr = product; ptr < product+3; ptr++) The following statements also behave in the similar fashion.
*ptr–>p Fetches whatever p points to.
scanf(“%s %d %f”, ptr–>name, &ptr–>number, &ptr–>price);
*ptr–>p++ Increments p after accessing whatever it points to.
printf(“\nOUTPUT\n\n”); (*ptr–>p)++ Increments whatever p points to.
ptr = product; *ptr++–>p Increments ptr after accessing whatever it points to.
while(ptr < product + 3) In the previous chapter, we discussed about passing of a structure as an argument to a function.
{ We also saw an example where a function receives a copy of an entire structure and returns it after
working on it. As we mentioned earlier, this method is inefficient in terms of both, the execution speed
printf(“%–20s %5d %10.2f\n”,
and memory. We can overcome this drawback by passing a pointer to the structure and then using this
ptr–>name, pointer to work on the structure members. Consider the following function:
ptr–>number, print_invent(struct invent *item)
ptr–>price); {
ptr++; printf(“Name: %s\n”, item->name);
} printf(“Price: %f\n”, item->price);
} }
This function can be called by
Output print_invent(&product);
The formal argument item receives the address of the structure product and therefore it must be
INPUT declared as a pointer of type struct invent, which represents the structure of product.
Washing_machine 5 7500
368 Programming in C Pointers 369

int (*rowptr)[SUBJECTS+1] = array;


ALWAys ReMeMBeR Note that array is the formal argument whose values are replaced by the values of the actual argument
marks. The parentheses around *rowptr makes the rowptr as a pointer to an array of SUBJECTS+1
∑ Only an address of a variable can be stored in a pointer variable. [Lo 11.1] integers. Remember, the statement
∑ Do not store the address of a variable of one type into a pointer variable of another type. [Lo 11.1] int *rowptr[SUBJECTS+1];
∑ The value of a variable cannot be assigned to a pointer variable. [Lo 11.1] would declare rowptr as an array of SUBJECTS+1 elements.
∑ A very common error is to use (or not to use) the address operator (&) and the indirection operator When we increment the rowptr (by rowptr+1), the incrementing is done in units of the size
(*) in certain places. Be careful. The compiler may not warn such mistakes. [Lo 11.1] of each row of array, making rowptr point to the next row. Since rowptr points to a particular row,
∑ Remember that the definition for a pointer variable allocates memory only for the pointer variable, (*rowptr)[x] points to the xth element in the row.
not for the variable to which it is pointing. [Lo 11.1]
∑ A pointer variable contains garbage until it is initialized. Therefore, we must not use a pointer Program
variable before it is assigned, the address of a variable. [Lo 11.2] #define STUDENTS 5
∑ It is an error to assign a numeric constant to a pointer variable. [Lo 11.2]
#define SUBJECTS 4
∑ It is an error to assign the address of a variable to a variable of any basic data types. [Lo 11.2]
∑ A proper understanding of a precedence and associativity rules is very important in pointer #include <string.h>
applications. For example, expressions like *p++, *p[ ], ( *p)[ ], (p).member should be carefully
used. [Lo 11.4] main()
∑ Be careful while using indirection operator with pointer variables. A simple pointer uses single {
indirection operator (*ptr) while a pointer to a pointer uses additional indirection operator symbol char name[STUDENTS][20];
(**ptr). [Lo 11.4]
int marks[STUDENTS][SUBJECTS+1];
∑ When an array is passed as an argument to a function, a pointer is actually passed. In the
header function, we must declare such arrays with proper size, except the first, which is optional.
[Lo 11.5] printf(“Input students names & their marks in four subjects\n”);
∑ If we want a called function to change the value of a variable in the calling function, we must pass get_list(name, marks, STUDENTS, SUBJECTS);
the address of that variable to the called function. [Lo 11.6] get_sum(marks, STUDENTS, SUBJECTS+1);
∑ When we pass a parameter by address, the corresponding formal parameter must be a pointer
printf(“\n”);
variable. [Lo 11.6]
∑ It is an error to assign a pointer of one type to a pointer of another type without a cast (with an print_list(name,marks,STUDENTS,SUBJECTS+1);
exception of void pointer). [Lo 11.6] get_rank_list(name, marks, STUDENTS, SUBJECTS+1);
printf(“\nRanked List\n\n”);
print_list(name,marks,STUDENTS,SUBJECTS+1);
BRief CAses }
/* Input student name and marks */
1. Processing of Examination Marks [LO 11.2, 11.5, 11.6 H] get_list(char *string[ ],
Marks obtained by a batch of students in the Annual Examination are tabulated as follows: int array [ ] [SUBJECTS +1], int m, int n)
Student name Marks obtained {
S. Laxmi 45 67 38 55
int i, j, (*rowptr)[SUBJECTS+1] = array;
V.S. Rao 77 89 56 69
for(i = 0; i < m; i++)
- ----
It is required to compute the total marks obtained by each student and print the rank list based on {
the total marks. scanf(“%s”, string[i]);
The program in Fig. 11.15 stores the student names in the array name and the marks in the array for(j = 0; j < SUBJECTS; j++)
marks. After computing the total marks obtained by all the students, the program prepares and prints scanf(“%d”, &(*(rowptr + i))[j]);
the rank list. The declaration
}
int marks[STUDENTS][SUBJECTS+1];
}
defines marks as a pointer to the array’s first row. We use rowptr as the pointer to the row of marks.
/* Compute total marks obtained by each student */
The rowptr is initialized as follows:
370 Programming in C Pointers 371

get_sum(int array [ ] [SUBJECTS +1], int m, int n) printf(“%–20s”, string[i]);


{ for(j = 0; j < n; j++)
int i, j, (*rowptr)[SUBJECTS+1] = array; printf(“%5d”, (*(rowptr + i))[j]);
for(i = 0; i < m; i++) printf(“\n”);
{ }
(*(rowptr + i))[n-1] = 0; }
for(j =0; j < n-1; j++) /* Exchange of integer values */
(*(rowptr + i))[n-1] += (*(rowptr + i))[j]; swap_int(int *p, int *q)
} {
} int temp;
temp = *p;
/* Prepare rank list based on total marks */ *p = *q;
*q = temp;
get_rank_list(char *string [ ], }
int array [ ] [SUBJECTS + 1]
int m, /* Exchange of strings */
int n) swap_string(char s1[ ], char s2[ ])
{ {
int i, j, k, (*rowptr)[SUBJECTS+1] = array; char swaparea[256];
char *temp; int i;
for(i = 0; i < 256; i++)
for(i = 1; i <= m–1; i++)
swaparea[i] = ‘\0’;
for(j = 1; j <= m–i; j++)
i = 0;
if( (*(rowptr + j–1))[n–1] < (*(rowptr + j))[n–1])
while(s1[i] != ‘\0’ && i < 256)
{
{
swap_string(string[j-1], string[j]);
swaparea[i] = s1[i];
i++;
for(k = 0; k < n; k++)
}
swap_int(&(*(rowptr + j–1))[k],&(*(rowptr+j))[k]);
i = 0;
}
while(s2[i] != ‘\0’ && i < 256)
}
{
/* Print out the ranked list */
s1[i] = s2[i];
print_list(char *string[ ], s1[++i] = ‘\0’;
int array [] [SUBJECTS + 1], }
int m, i = 0;
int n) while(swaparea[i] != ‘\0’)
{ {
int i, j, (*rowptr)[SUBJECTS+1] = array; s2[i] = swaparea[i];
for(i = 0; i < m; i++) s2[++i] = ‘\0’;
{ }
}
372 Programming in C Pointers 373

Output float p_increment, value;


int q_increment;
Input students names & their marks in four subjects
S.Laxmi 45 67 38 55 struct stores item = {“XYZ”, 25.75, 12};
V.S.Rao 77 89 56 69 struct stores *ptr = &item;
A.Gupta 66 78 98 45
S.Mani 86 72 0 25 printf(“\nInput increment values:”);
R.Daniel 44 55 66 77 printf(“ price increment and quantity increment\n”);
scanf(“%f %d”, &p_increment, &q_increment);
S.Laxmi 45 67 38 55 205
V.S.Rao 77 89 56 69 291 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - */
A.Gupta 66 78 98 45 287 update(&item, p_increment, q_increment);
S.Mani 86 72 0 25 183 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - */
R.Daniel 44 55 66 77 242 printf(“Updated values of item\n\n”);
printf(“Name : %s\n”,ptr–>name);
Ranked List printf(“Price : %f\n”,ptr–>price);
V.S.Rao 77 89 56 69 291 printf(“Quantity : %d\n”,ptr–>quantity);
A.Gupta 66 78 98 45 287
R.Daniel 44 55 66 77 242 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - */
S.Laxmi 45 67 38 55 205 value = mul(&item);
S.Mani 86 72 0 25 183 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - */
printf(“\nValue of the item = %f\n”, value);
Fig. 11.15 Preparation of the rank list of a class of students }

2. Inventory Updating [LO 11.2, 11.6 M]


void update(struct stores *product, float p, int q)
The price and quantity of items stocked in a store changes every day. They may either increase or {
decrease. The program in Fig. 11.16 reads the incremental values of price and quantity and computes product–>price += p;
the total value of the items in stock.
product–>quantity += q;
The program illustrates the use of structure pointers as function parameters. &item, the address of
}
the structure item, is passed to the functions update() and mul(). The formal arguments product and
stock, which receive the value of &item, are declared as pointers of type struct stores. float mul(struct stores *stock)
{
Program return(stock–>price * stock–>quantity);
struct stores }
{
char name[20]; Output
float price;
int quantity; Input increment values: price increment and quantity increment
}; 10 12
main() Updated values of item
{
void update(struct stores *, float, int); Name : XYZ
374 Programming in C

Price : 35.750000
Quantity : 24

Value of the item = 858.000000

Fig. 11.16 Use of structure pointers as function parameters

RevieW Questions
11.1 State whether the following statements are true or false.
(a) Pointer constants are the addresses of memory locations. [LO 11.1 M]
(b) The underlying type of a pointer variable is void. [LO 11.1 M]
(c) Pointer variables are declared using the address operator. [LO 11.2 E]
(d) It is possible to cast a pointer to float as a pointer to integer. [LO 11.2 M]
(e) Pointers to pointers is a term used to describe pointers whose contents are the address of
another pointer. [LO 11.3 E]
(f) A pointer can never be subtracted from another pointer. [LO 11.4 E]
(g) An integer can be added to a pointer. [LO 11.4 M]
(h) Pointers cannot be used as formal parameters in headers to function definitions. [LO 11.6 E]
(i) When an array is passed as an argument to a function, a pointer is passed. [LO 11.6 M]
(j) Value of a local variable in a function can be changed by another function. [LO 11.6 M]
11.2 Fill in the blanks in the following statements:
(a) A pointer variable contains as its value the _____ of another variable. [LO 11.1 E]
(b) The _____operator returns the value of the variable to which its operand points. [LO 11.1 E]
(c) The ______operator is used with a pointer to de-reference the address contained in the
pointer. [LO 11.2 M]
(d) The pointer that is declared as ______cannot be de-referenced. [LO 11.2 M]
(e) The only integer that can be assigned to a pointer variable is ______. [LO 11.4 M]
11.3 What is a pointer? How can it be initialized? [LO 11.1, 11.2 E]
11.4 A pointer in C language is [LO 11.1 E]
(a) address of some location
(b) useful to describe linked list
(c) can be used to access elements of an array
(d) All of the above.
11.5 Explain the effects of the following statements: [LO 11.2 M]
(a) int a, *b = &a;
(b) int p, *p;
(c) char *s;
(d) a = (float *) &x);
(e) double(*f)();
11.6 Distinguish between (*m)[5] and *m[5]. [LO 11.5 M]
11.7 Given the following declarations: [LO 11.4 H]
int x = 10, y = 10;
int *p1 = &x, *p2 = &y;

You might also like