C Program to Check Whether a Character is a Vowel or Consonant
#include <stdio.h>
#include <ctype.h> // for using tolower() function
int main() {
char ch;
// Input a character from the user
printf("Enter a character: ");
scanf("%c", &ch);
// Convert the character to lowercase to simplify comparisons
ch = tolower(ch);
// Check if the character is a vowel or consonant
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
printf("%c is a vowel.\n", ch);
} else if ((ch >= 'a' && ch <= 'z')) { // Check if it's a letter
printf("%c is a consonant.\n", ch);
} else {
printf("%c is not a letter.\n", ch);
}
return 0;
}
Explanation:
- tolower() function: Used to convert the character to lowercase, so we only need to check for vowels in lowercase.
- Vowel check: We check if the character is one of ‘a’, ’e’, ‘i’, ‘o’, or ‘u’.
- Consonant check: If the character is a letter but not a vowel, it is a consonant.
- If the input is not a letter (i.e., not in the range ‘a’ to ‘z’), the program informs that it is not a letter.
You can run this program and input a character to see whether it’s a vowel or consonant.
Example 1: Input and Output
Input:
Enter a character: A
Output:
a is a vowel.
Example 2: Input and Output
Input:
Enter a character: b
Output:
b is a consonant.
Example 3: Input and Output
Input:
Enter a character: 1
Output:
1 is not a letter.
How it works:
- Example 1: The user inputs ‘A’, which is converted to lowercase ‘a’. The program identifies ‘a’ as a vowel.
- Example 2: The user inputs ‘b’, and since ‘b’ is a consonant, the program identifies it correctly.
- Example 3: The user inputs ‘1’, which is not a letter, so the program indicates that it’s not a letter.
Last updated on