Beginner · cctype

Count the Vowels

Read a word and count its vowels. The judge includes uppercase input on purpose — that is the whole lesson.

At a glanceWalk the string and test each character against a, e, i, o, u in both cases — the hidden tests include all-uppercase input, so a lowercase-only check undercounts.

Problem

Input: One word (letters only, may be uppercase).

Output: How many vowels it contains, ignoring case.

Sample:

InputOutput
AEIOU5

Your solution

main.cpp — your solution
Custom input for "Run my input"

Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.

Stuck? Hints

Hint 1 — tolower is your friend

From <cctype>: char c = tolower(s[i]); then compare with the five lowercase vowels.

Hint 2 — Loop condition

for (int i = 0; s[i] != '\0'; i++) — stop at the terminator instead of using a fixed length.

Solution (try it first!)
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

int main() {
    char s[100];
    cin >> s;
    int count = 0;
    for (int i = 0; s[i] != '\0'; i++) {
        char lower = tolower(s[i]);
        if (lower == 'a' || lower == 'e' || lower == 'i' ||
            lower == 'o' || lower == 'u') count++;
    }
    cout << count << endl;
    return 0;
}

Without tolower, the AEIOU test returns 0. Next: 2D arrays.

Deep dive

Why this works

Classification by membership — is this character in a set? — is the base case of every tokenizer and parser you will ever meet.

The cost

O(n·k) with k = 5 comparisons, i.e. O(n). A 256-entry lookup table makes k constant.

Where it goes wrong

  • Counting only lowercase misses 'A'. Normalise with tolower, or test both cases.
  • tolower is locale-dependent: in a Turkish locale 'I' does not lowercase to 'i'.

Next step

Character arrays at scale: Reverse a String.

Two things to remember

  • Normalise case before comparing characters.
  • Membership tests want a table, not an if-chain.
🐞 This version fails — open it and try

Only counts lowercase vowels

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char s[100];
    cin >> s;
    int n = strlen(s), c = 0;
    for (int i = 0; i < n; i++) {
        if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u') c++;
    }
    cout << c << endl;
    return 0;
}