Computer >> Computer tutorials >  >> Programming >> C programming

How to count number of vowels and consonants in a string in C Language?


Problem

How to write a C program to count numbers of vowels and consonants in a given string?

Solution

The logic that we will write to implement the code to find vowels and consonants is −

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' )

If this condition is satisfied, we try to increment the vowels. Or else, we increment the consonants.

Example

Following is the C program to count the number of vowels and consonants in a string −

/* Counting Vowels and Consonants in a String */
#include <stdio.h>
int main(){
   char str[100];
   int i, vowels, consonants;
   i = vowels = consonants = 0;
   printf("Enter any String\n : ");
   gets(str);
   while (str[i] != '\0'){
      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' ){
      vowels++;
      }
      else
         consonants++;
         i++;
   }
   printf("vowels in this String = %d\n", vowels);
   printf("consonants in this String = %d", consonants);
   return 0;
}

Output

When the above program is executed, it produces the following result −

Enter any String: TutoriasPoint
vowels in this String = 6
consonants in this String = 7