C Program to Check a Character is a Vowel or Consonant

CodingTute

C Program to Check a Character is a Vowel or Consonant

In this example, you will learn to check a given character is vowel or consonant.

We all know there are 26 alphabets in which there are 5 vowels and 21 consonants. The five vowels are A, E, I, O, and U.

C Program to Check Vowel or Consonant

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

int main() {
   char ch;
   int lvowel, uvowel;
   printf("Enter an alphabet: ");
   scanf("%c", &ch);
   
   // isalpha(ch) evaluates 1 if variable ch is alphabet   
   if (!isalpha(ch))
      printf("%c is not an alphabet.", ch);
   else{
 
       // if variable ch is a uppercase vowel, it evaluates to 1 
       uvowel = (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');
    
       // if variable ch is a lowercase vowel, it evaluates to 1 
       lvowel = (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
    
       if (lvowel || uvowel)
          printf("%c is a vowel.", ch);
       else
          printf("%c is a consonant.", ch);
   }
   return 0;
}

Output

Enter an alphabet: A
A is a vowel.

Explanation

Firstly we read input from the user and store it in a variable ch.

Now we will check the character entered by the user is an alphabet or not by using the predefined function isalpha() defined under ctype.h library.

isalpha() function returns 1 if the character passed to it is an alphabet, else it will return 0.

If the user entered input is not an alphabet then we will print the entered character is not an alphabet and terminates the program.

If the user entered input is an alphabet then we will initiate the process of evaluating the given character is vowel or not.

The user input can be a lowercase letter or an uppercase letter. In our program, we check for lowercase vowels and uppercase vowels because we can minimize the evaluation expression.

uvowel = (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');

The above expression evaluates to 1 stored to uvowel variable if the input alphabet is an upper case vowel.

lvowel = (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');

The above expression evaluates to 1 and stored lvowel variable if the input alphabet is a lower case vowel.

if (lvowel || uvowel)
     printf("%c is a vowel.", ch);
else
     printf("%c is a consonant.", ch);

In the above conditional statement, we will check it is lower case vowel or upper case vowel. If it’s found to be vowel then we will print the given alphabet is vowel else we print it is a consonant.