Monday, 27 November 2017

C Program to count number of words

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*/

No comments:

Post a Comment

Featured Post

TCS Latest Test Patern ( For On-Campus Drives )

Tata Consultancy Services is software services consulting company whose  headquarter is situated in Mumbai, India. It is the Asia’s larges...