Tuesday, April 30, 2013

c Program to Count Number of Words and Number of Characters in a String

//Program to Count Number of Words and Number of Characters in a String
#include <stdio.h>
#include <string.h>
main()
{
char str[20];
int i=0, word=0, chr=0;
printf("\nEnter any string: ");
gets(str);
while (str[i] != '\0')
{
if (str[i] == ' ')
{
word++;
chr++;
}
else
chr++;
i++;
}
printf("\nNumber of characters: %d", chr);
printf("\nNumber of words: %d", word+1);
getch();
}
Output of above program :

Enter string : c programming codes
Number of characters in string : 19
Number of words in string : 3

1 comment: