To count the number of words in a given string
by Ranjith | December 4th, 2008.This is the program to count number of words in the entered sentence.
Logic: The logic behind this program is checking if the character in the sentence is a ‘blank’ and with the conditions that the next is not a blank character, or current character position is not equal to length of the sentence. If so, variable ‘words’ is incremented by one as one new word found.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[50];
int words = 0, len = 0, i;
clrscr();
printf(“\n\n\t ENTER A STRING…: “);
gets(str);
while(str[len]!=’\0′)
len++;
len–;
for(i=0;i<=len;i++)
{
if ( ( str[i] == ‘ ‘ && str[i+1] != ‘ ‘ ) || i == len )
words++;
}
printf(“\n\t NUMBER OF WORDS IN THE ABOVE SENTENCE IS…: %d”, words);
getch();
}
Download exe and source code here.




















April 2nd, 2010 at 11:33 pm
Thax dear your code is totally correct