UncleCoder.com

UncleCoder.com

Free programming examples and instructions

C program to count the number of words in a string using function

C program for how to find number of words in a string

by Krishna viswambharan


Posted on 10 Oct 2017 Category: C Views: 276

Edited on 09 Feb 2018


C program to count the number of words in a string using function

This is a C program to count number of words in a string.  Here each word is identified using a white space between the words.  This program takes string as input and gives the word count as the output.

Source code for the program is given as 

#include <stdio.h>
#include <conio.h>
#include <string.h>
int length(char []);     //function prototype
void main()
{
   char name[50],c=1;
   printf(“Enter the string :”);
   gets(name);
   c=length(name);     //function call
   printf(“\nNumber of words=%d”,c);
   getch();
}
int length(char x[])          //function definition
{
   int i=0,c=1;
   while(x[i]!=’\0’)
   {
       if(x[i]== ‘ ‘)        //if space occurs count increments
          c=c+1;   
       i=i+1;
   }
   return(c)
} 

 

In this program  , if statement it checks whether there is a space or not. If a space occurs then the count value increments and the searching continues until x[i] equal to NULL or ‘\0’.

output

 



Leave a Comment:


Advertisement