A C program to count number of vowels, consonants & spaces in a given string

By | October 8, 2013

Let’s identify variables needed for this program.

In this program, we need several variables to store large sentence and count the number of occurrences in the given sentence.

First variable will be the one which will save the sentence given and it will be S[]. Keeping the square bracket blank means it will take the size automatically against the initialized value, But we can not keep the brackets blank without assignment of values to any kind of array form. Next is a pointer which will hold the address of S[]  and that will be *PTR which will be used for moving from start to end of the string given and SP,VO,CO will be used to store the total count of SPACES, VOWELS, CONSONANTS respectively so in all Five variables.
The identified variables are S[],*PTR,SP,VO,CO.

Now, Selection of data type will be int data type due to the values expected for counting are decimals and they will be holding smaller values so int data type is sufficient for SP,VO,CO. Selection of data type will be char data type due to string or sentence is a character array and we don’t have any string data type so char data type is selected for S[] and *PTR pointers are always of same data type.

In this program variables used for storing counts is initialized to zero. As we all now the word is differentiated by a space and vowels are all the words starting with A,E,I,O,U  and all other are consonants.

Here we are checking for space incrementing SP i.e. counting space, then if any word after space is A or E or I or O or U, if yes incrementing VO i.e. counting vowel and else incrementing CO i.e. counting consonants.

 Source code
```SP=VO=CO=0;
while(*PTR)
{
if(*PTR==' ')
{
SP++;

if(*(PTR+1)=='a'||*(PTR+1)=='A'||\
*(PTR+1)=='e'||*(PTR+1)=='E'||\
*(PTR+1)=='i'||*(PTR+1)=='I'||\
*(PTR+1)=='o'||*(PTR+1)=='O'||\
*(PTR+1)=='u'||*(PTR+1)=='U')

VO++;
else
CO++;
}

PTR++;
}```

Finally print the Numbers as counts of Vowels, Consonants and Spaces at the end of the program.

C program code :

 Source code
`#include<stdio.h>void main(){ char *PTR,S[]="When it HURTS to look back, and \                you're SCARED to look ahead, you can look beside\                you and your BEST FRIEND will be there"; int SP,VO,CO; clrscr(); printf("\nTHE GIVEN STRING IS :-\n\t  %s\n",S); PTR=&S; SP=VO=CO=0; while(*PTR)     {      if(*PTR==' ')      {         SP++;          if(*(PTR+1)=='a'||*(PTR+1)=='A'||\         *(PTR+1)=='e'||*(PTR+1)=='E'||\         *(PTR+1)=='i'||*(PTR+1)=='I'||\         *(PTR+1)=='o'||*(PTR+1)=='O'||\         *(PTR+1)=='u'||*(PTR+1)=='U')         VO++;         else        CO++;      }        PTR++;     }`

SCREEN SHOTS:-