In English, there are 5 vowel letters and 21 consonant letters. In lowercase alphabets, ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ are vowels and all other characters (‘b’, ‘c’, ‘d, ‘f’….) are consonants. Similarly in uppercase alphabets, ‘A’, ‘E’, ‘I’, ‘O’, and ‘U’ are vowels, and the rest of the characters are consonants.
In this article, we will learn how to write a C program to check if a character is a vowel or consonant.
Algorithm
The algorithm to check vowels and consonants is simple to understand and implement. Here,
- Check if (ch == ‘a’ || ch == ‘A’ || ch == ‘e’ || ch == ‘E’ || ch == ‘i’ || ch == ‘I’ || ch == ‘o’ || ch == ‘O’ || ch == ‘u’ || ch == ‘U’), the character is a vowel.
- Else, the character is a consonant.
C Program to Check Vowel or Consonant
Below is the C program to find if a character is a vowel or consonant using an if-else statement.
// C program to check if a character // is a vowel or consonant #include <stdio.h> // Driver code int main()
{ char ch = 'A' ;
// Checking if the character ch
// is a vowel or not.
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E'
|| ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O'
|| ch == 'u' || ch == 'U' ) {
printf ( "The character %c is a vowel.\n" , ch);
}
else {
printf ( "The character %c is a consonant.\n" , ch);
}
return 0;
} |
The character A is a vowel.
Complexity Analysis
- Time Complexity: O(1)
- Auxiliary Space: O(1)
Check Vowel or Consonant using strchr() Function
In the below C program, the str array contains a list of vowels. The strchr() function is used to search for the entered character in the vowels array. If the character is found, the isVowel function returns 1, otherwise, it returns 0.
// C program to check vowel or consonant #include <stdio.h> #include <string.h> int isVowel( char ch)
{ // Make the list of vowels
char vowels[] = "aeiouAEIOU" ;
return ( strchr (vowels, ch) != NULL);
} // Driver Code int main()
{ if (isVowel( 'a' ))
printf ( "a is vowel\n" );
else
printf ( "a is consonant\n" );
return 0;
} |
a is vowel
Complexity Analysis
- Time Complexity: O(1)
- Auxiliary Space: O(1)
Refer to the complete article Program to find if a character is vowel or Consonant for more methods to check if a character is a vowel or consonant.