C Program to Count Number of Words in a String

In this tutorial, i am going to show you how to count number of words in a given string using for loop, while loop, and function.

All C Programs to Count Number of Words in a String

  • C Program to Count Number of Words in a String using for loop
  • C Program to Count Number of Words in a String using while loop
  • C Program to Count Number of Words in a String using function

C Program to Count Number of Words in a String using for loop

/* C Program to Count Total Number of Words in a String */
 
#include <stdio.h>
#include <string.h>
 
int main()
{
  	char str[100];
  	int i, totalwords;
  	totalwords = 1;
 
  	printf("\n Please Enter any String :  ");
  	gets(str);
  	 	   	
  	for(i = 0; str[i] != '\0'; i++)
	{
		if(str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
		{
			totalwords++;	
		} 
	}	
	printf("\n The Total Number of Words in this String %s  = %d", str, totalwords);
	
  	return 0;
}

The result of the above c program; as follows:

Please Enter any String :  hello developer
The Total Number of Words in this String hello developer  = 2

C Program to Count Number of Words in a String using while loop

/* C Program to Count Total Number of Words in a String */
 
#include <stdio.h>
#include <string.h>
 
int main()
{
  	char str[100];
  	int i, totalwords;
  	totalwords = 1;
  	i = 0;
 
  	printf("\n Please Enter any String :  ");
  	gets(str);
  	 	   	
  	while(str[i] != '\0')
	{
		if(str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
		{
			totalwords++;	
		} 
		i++;
	}	
	printf("\n The Total Number of Words in this String %s  = %d", str, totalwords);
	
  	return 0;
}

The output of the above c program; as follows:

Please Enter any String :  hy dud
The Total Number of Words in this String hy dud  = 2

C Program to Count Number of Words in a String using function

/* C Program to Count Total Number of Words in a String */
 
#include <stdio.h>
#include <string.h>
 
int Count_TotalWords(char *str);
 
int main()
{
  	char str[100];
  	int totalwords;
  	totalwords = 1;
 
  	printf("\n Please Enter any String :  ");
  	gets(str);
  	 	   	
  	totalwords = Count_TotalWords(str);
  
	printf("\n The Total Number of Words in this String %s  = %d", str, totalwords);
	
  	return 0;
}
int Count_TotalWords(char *str)
{
	int i, totalwords;
  	totalwords = 1;
  	
	for(i = 0; str[i] != '\0'; i++)
	{
		if(str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
		{
			totalwords++;	
		} 
	}
	return totalwords;
}

The result of the above c program; as follows:

Please Enter any String :  hello dear sir
The Total Number of Words in this String hello dear sir  = 3

Be First to Comment

Leave a Reply

Your email address will not be published.