Determining whether a given character is a vowel or a consonant is a common exercise in programming. This article explains two popular methods to achieve this: using if-else
statements and switch-case
statements.
if-else
switch-case
Checking if a character is a vowel or a consonant is a basic problem that introduces decision-making constructs in programming. This guide provides two approaches in C for solving this problem effectively.
a
, e
, i
, o
, u
(both uppercase and lowercase) are vowels.Special characters, digits, and whitespace are not considered in this classification.
if-else
This method uses conditional statements to compare the input character against all possible vowels. If it matches, the character is identified as a vowel; otherwise, it is categorized as a consonant.
switch-case
This method involves matching the character against specific cases for vowels. If no match is found, it defaults to identifying the character as a consonant.
if-else
#include <stdio.h>
void checkVowelOrConsonant(char ch) {
// Convert to lowercase for uniformity
char lower = (ch >= 'A' && ch <= 'Z') ? ch + 32 : ch;
if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower == 'u') {
printf("%c is a vowel.\n", ch);
} else if ((lower >= 'a' && lower <= 'z')) {
printf("%c is a consonant.\n", ch);
} else {
printf("%c is not an alphabet.\n", ch);
}
}
int main() {
char ch;
// Input from user
printf("Enter a character: ");
scanf(" %c", &ch);
checkVowelOrConsonant(ch);
return 0;
}
switch-case
#include <stdio.h>
void checkVowelOrConsonantSwitch(char ch) {
// Convert to lowercase for uniformity
char lower = (ch >= 'A' && ch <= 'Z') ? ch + 32 : ch;
switch (lower) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%c is a vowel.\n", ch);
break;
default:
if (lower >= 'a' && lower <= 'z') {
printf("%c is a consonant.\n", ch);
} else {
printf("%c is not an alphabet.\n", ch);
}
}
}
int main() {
char ch;
// Input from user
printf("Enter a character: ");
scanf(" %c", &ch);
checkVowelOrConsonantSwitch(ch);
return 0;
}
Using both if-else
and switch-case
provides flexibility and understanding of decision-making constructs in C. The if-else
method is straightforward, while switch-case
is more structured and scalable for additional classifications.