278 Programming and Data Structures
Explanation In the above program standard string functions s trcmp () and s trcpy () are used.
The s trcmp () function compares two successive city names. If their ASCII difference is greater than
zero city names are exchanged. This is accomplished by the body of the i f statement. Thus, on
execution of the program cities are displayed in the alphabetical order.
8.43 / 8.44 Write a program to find number of words in a given statement. Exclude spaces
between them.
# include <stdio.h>
# include <conio.h>
void main ()
{
char text [30] ;
int count=0,i=0;
clrscrO ;
printf ("Enter The Line of Text n ");
printf ("G iv e One Space After Each w ordn");
gets(text);
while (tex t[i++ ]!= '0 ')
if(text[i]==32 I I text[i]= = '0 ')
count++;
printf ("The Number o f words in line = %dn",count);
}
OUTPUT:
Enter The Line of Text
Give One Space After Each word
Read Books
The Number of words in line = 2
Explanation In the above program string is entered. It is known that the single space separates two
consecutive words. The logic for finding the number of words in a statement is to detect number of
spaces and N U L L character. For example, in a statement "C IS A PROGRAMMING LANGUAGE" there are
four spaces and a NULL character when the string is terminated. Thus, the total characters are five
(4+1). The i f statement counts number of spaces and NULL character in the string.
OR
# include <stdio.h>
# include <conio.h>
void main ()
{
char text [30];
int count=0,i=0;
clrscrO ;
printf ("Enter Text B e low :");
gets(text);
while (tex t[i]!= '0 ')