Program to find number of words,vowels,spaces,special chars and consonants in sentence using C

C language provides many libraries to handle strings. The libraries that we are going to be using are ctype and string. If you are working in C and you require to manipulate a string, ctype and string header files are your friends! Make use of them.

Explanation

The functions of ctype.h used in the program are:

  1. isalpha() – Checks whether the reading character is an alphabet
  2. isspace() – Check for white space
  3. ispunc() – Checks whether the character is a punctuation [character that is not an alphabet]

The functions of string.h header used in code:

  1. strlen() – Checks the length of the string and return a number
  2. gets() – helps in input of a string from the console. It can take any number of strings [ Will not run in linux gcc, Deprecated due to security reasons. It causes buffer overflow!  ]

Let’s get on the code:

CODE:

#include<stdio.h>
#include<ctype.h>
#include<string.h>

void main(){
	char s[100];
	int vowels=0,cons=0,space=0,punc=0,i,len;
	printf("Enter the statement:\n");
	gets(s);
	len=strlen(s);
	for(i=0;i<len;i++){
		if(isalpha(s[i])){
			if(s[i]=='a' || s[i]=='e' || s[i]=='i'|| s[i]=='o'|| s[i]=='u'){
				vowels++;
			}
			else{
				cons++;
			}
		}
	if(isspace(s[i])){
		space++;
	}
	if(ispunct(s[i]))
	{
		punc++;
	}
	}
	printf("\nNo of words = %d",space+1);
	printf("\nNo of vowels = %d",vowels);printf("\nNo of consonants = %d",cons);
	printf("\nNo of spaces = %d",space);printf("\nNo of special chars = %d",punc);
}

 

OUTPUT:

program to find number of vowel and consonants in C

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.