Checking whether a character is a vowel or consonant is a fundamental problem in c program to check whether a character is vowel or consonant, conditional statements, and the basics of input/output operations. In this discussion, we will explore how to implement a simple C program to determine whether a given character is a vowel or a consonant.
Understanding Vowels and Consonants
In the English alphabet, vowels include:
A, E, I, O, U (both uppercase and lowercase: a, e, i, o, u)
All other alphabetic characters are considered consonants. Any character that is not a letter (e.g., numbers, symbols) should be handled separately to ensure robust program behavior.
C Program Implementation
Below is a simple C program to check whether an input character is a vowel or consonant:
c
Copy
Edit
#include <stdio.h>
int main() {
char ch;
// Input from user
printf("Enter a character: ");
scanf("%c", &ch);
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
printf("%c is a vowel.\n", ch);
}
// Check if it is an alphabet but not a vowel (consonant)
else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
printf("%c is a consonant.\n", ch);
}
// If it is not an alphabet
else {
printf("%c is not an alphabet.\n", ch);
}
return 0;
}
Explanation of the Code
The program first declares a char variable to store user input.
The scanf function reads a single character from the user.
A series of if-else conditions determine if the character is a vowel by checking against both uppercase and lowercase vowels.
If the character is not a vowel but falls within the range of alphabetic characters (A-Z or a-z), it is classified as a consonant.
If the input is neither a vowel nor a consonant (e.g., a digit or symbol), the program informs the user accordingly.
Sample Output
less
Copy
Edit
Enter a character: a
a is a vowel.
less
Copy
Edit
Enter a character: B
B is a consonant.
pgsql
Copy
Edit
Enter a character: 1
1 is not an alphabet.
Enhancements and Variations
Convert uppercase to lowercase using tolower() function before comparison to simplify conditions.
Use switch instead of if-else for an alternative implementation.
Extend the program to handle multiple characters using loops.