C+Python For CT-2
C+Python For CT-2
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”) ;
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
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
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
}
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
Output
}
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]
= Â
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
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 }
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
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
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( ) */ — — — — — — — — — — — — — — — — — — — — — — —
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
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
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
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]
x = x+1;
Curve
printf(“x = %d\n”, x);
}
Output
x = 1 b
f(x)
x = 2 h1 h2
x = 3
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
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
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
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
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
Price : 35.750000
Quantity : 24
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;