Counting vowels and consonants
What you'll learn: How to iterate through a string and use conditional logic to categorize and count specific types of characters.
The Scanner Analogy
Imagine you are a security guard at a stadium gate. Your job is to count how many adults and how many children enter. As each person walks by, you look at them, decide which category they fit into, and click a handheld counter for that group.
Processing a string in C works exactly like this. The string is the line of people, your for loop is the gate they walk through, and your if-else statements are the mental rules you use to decide which counter to increment.
Setting Up the Counters
To count vowels and consonants, we need two integer variables initialized to zero. As we move through the string index by index, we check if the current character is a letter. If it is, we check if it belongs to the "vowel" family (a, e, i, o, u). If it doesn't, it must be a consonant.
We often use the tolower() function from the <ctype.h> library. This simplifies our logic so we don't have to check for both 'A' and 'a'—we just turn everything into lowercase before checking.
The Implementation
Here is how you can build a simple character counter:
#include <stdio.h>
#include <ctype.h>
int main() {
char text[] = "Hello World";
int vowels = 0;
int consonants = 0;
for (int i = 0; text[i] != '\0'; i++) {
char c = tolower(text[i]);
// First, ensure it's a letter of the alphabet
if (c >= 'a' && c <= 'z') {
// Check if it's a vowel
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
} else {
// If it's a letter but not a vowel, it's a consonant
consonants++;
}
}
}
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
Why Order Matters
Notice that we check c >= 'a' && c <= 'z' first. Strings often contain spaces, exclamation points, or numbers. If we didn't filter for letters first, our code might mistakenly count a punctuation mark as a consonant. By nesting our vowel check inside a general letter check, we ensure our counters stay accurate.
Key takeaway
To count specific characters, loop through the string and use nested if statements to filter out non-letters before sorting vowels from consonants.