C Program to Count Vowels and Consonants in a String

In this post, you will learn how to count the number of vowels and consonants in an entered sentence. The vowels are a, e, i, o, and u, and the rest of the letters are consonants.

Let's write a C program to count vowels and consonants in a string.

C Program to Count Vowels and Consonants in a String

Let's create a file named countvowelsandcons.c and add the following source code to it:
#include <stdio.h>
void main()
{
    char str[255];
    int  ctrV,ctrC,i;
   printf("Enter a sentence: ");
   gets(str);
    ctrV=ctrC=i=0;
    while(str[i]!='\0')
    {
	if((str[i] >=65 && str[i]<=90) || (str[i] >=97 && str[i]<=122))
	{
	        if(str[i]=='A' ||str[i]=='E' ||str[i]=='I' ||str[i]=='O' ||str[i]=='U' ||str[i]=='a' ||str[i]=='e' ||str[i]=='i' ||str[i]=='o' ||str[i]=='u')
            		ctrV++;
        	       else
            		ctrC++;
	}
       	i++;
    }
    printf("Number of vowels are : %d\nNumber of consonants are : %d\n",ctrV,ctrC);
}

To compile and run the above C program, you can use C Programs Compiler Online tool.

Output:

Enter a sentence: sourcecodeexamples
Number of vowels are : 8
Number of consonants are : 10


Comments