Count Vowels
Character classification combines traversal, normalization, and membership tests.
What is Count Vowels?
Character classification combines traversal, normalization, and membership tests.
Count vowels in a line of text.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "Code Utility"; int count = 0;
// strchr performs a compact membership check.
for (; *text; ++text) if (strchr("aeiou", tolower((unsigned char)*text))) ++count;
printf("vowels=%d\n", count);
}
vowels=5
C++
main.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string text = "Code Utility";
// count_if counts characters accepted by the predicate.
auto vowels = std::count_if(text.begin(), text.end(), [](unsigned char c) {
return std::string("aeiou").find(std::tolower(c)) != std::string::npos;
});
std::cout << "vowels=" << vowels << '\n';
}
vowels=5
C and C++ comparison
Convert each character to lowercase before checking the five vowel characters.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.