Cracking the Code: A Step-by-Step Guide to Identifying Vowels and Consonants
The Problem: Identifying Vowels and Consonants
In the English language, five alphabets – a, e, i, o, and u – are classified as vowels. All other alphabets, excluding these five, are considered consonants. Our task is to create a program that can differentiate between these two categories.
The Solution: A C++ Program
Let’s start by storing the user-input character in a variable ‘c’. We’ll then create two boolean variables: isLowerCaseVowel
and isUpperCaseVowel
. These will evaluate to true if ‘c’ is a lowercase or uppercase vowel, respectively, and false otherwise.
char c;
bool isLowerCaseVowel, isUpperCaseVowel;
// Initialize isLowerCaseVowel and isUpperCaseVowel based on the value of c
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
isLowerCaseVowel = true;
} else {
isLowerCaseVowel = false;
}
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
isUpperCaseVowel = true;
} else {
isUpperCaseVowel = false;
}
The Logic Behind the Code
If both isLowerCaseVowel
and isUpperCaseVowel
are true, we know that the character entered is a vowel. If not, it’s a consonant. But what if the user enters something other than an alphabet? That’s where the isalpha()
function comes in. This handy tool checks whether the input character is an alphabet or not. If it’s not, we’ll display an error message.
if (isalpha(c)) {
if (isLowerCaseVowel || isUpperCaseVowel) {
cout << "The character is a vowel.";
} else {
cout << "The character is a consonant.";
}
} else {
cout << "Error: Input is not an alphabet.";
}
Putting it All Together
With our program in place, we can now seamlessly identify vowels and consonants. Whether you’re a seasoned programmer or just starting out, this exercise is a great way to hone your skills and gain confidence in your coding abilities.
Take Your Skills to the Next Level
Want to take your programming skills to new heights? Try creating a program that can count the number of vowels, consonants, digits, and white spaces in a string. The possibilities are endless, and with practice, you’ll be well on your way to becoming a master coder.
- Count the number of vowels in a string
- Count the number of consonants in a string
- Count the number of digits in a string
- Count the number of white spaces in a string
Learn more about C++ programming