Write a C program to count number of words.
Example : Welcome to SimpleWay2Code ↵
3
#include<stdio.h>
int main()
{
char a[50];
int l,word=0,i=0;
printf("Enter A String: ");
gets(a);
for(l=0;a[l]!='\0';l++);
for(i=0;i<=l;i++)
{
if(a[i]==' ' && a[i+1]!=' ')
word++;
}
printf("%d",word+1);
return 0;
}
/* Explaination */
/* This program will help to count number of words in a line.
for(l=0;a[l]!='\0';l++) is used to calculate total number of characters. Its will help in Space checking condition in next loop. The condition if(a[i]==' ' && a[i+1]!=' ') is taken because if there are two spaces between two words then it will take it only as one space rather taking two space*/
Example : Welcome to SimpleWay2Code ↵
3
#include<stdio.h>
int main()
{
char a[50];
int l,word=0,i=0;
printf("Enter A String: ");
gets(a);
for(l=0;a[l]!='\0';l++);
for(i=0;i<=l;i++)
{
if(a[i]==' ' && a[i+1]!=' ')
word++;
}
printf("%d",word+1);
return 0;
}
/* Explaination */
/* This program will help to count number of words in a line.
for(l=0;a[l]!='\0';l++) is used to calculate total number of characters. Its will help in Space checking condition in next loop. The condition if(a[i]==' ' && a[i+1]!=' ') is taken because if there are two spaces between two words then it will take it only as one space rather taking two space*/
0 Comments