SECTION 16 / 17

Tutorial: count vowels and consonants in a word

2 min read

CountVowelsAndConsonants(X) receives one word card. For “reluctant”, start i = 1, Vcount = 0 and Ccount = 0. Inspect the ith letter. If it is a vowel, increase Vcount; ELSE increase Ccount. Then increase i outside both branches.

“reluctant” has 9 letters: e, u and a are the 3 vowels; r, l, c, t, n and t are the 6 consonants.
“reluctant” has 9 letters: e, u and a are the 3 vowels; r, l, c, t, n and t are the 6 consonants.
REAL COURSE DATA · THINK BEFORE EACH STEP

Count vowels and consonants

Trace the records, compare the methods and watch what changes. Back and Reset let you try again.

Ready

CURRENT RECORD X

Ready to begin

Choose Next step to follow the actual course records.

What we remember

Processed
0

Start with Next step. Predict what changes before reading the explanation.

Procedure CountVowelsAndConsonants(X):
    Letters = alphabetic letters of X.Word
    i = 1
    Vcount = 0
    Ccount = 0
    while i <= number of Letters:
        if lowercase(Letters[i]) is one of a, e, i, o, u:
            Vcount = Vcount + 1
        else:
            Ccount = Ccount + 1
        i = i + 1
    return (Vcount, Ccount)
End Procedure
iLetterBranchVcountCcount
1rELSE01
2eIF11
3lELSE12
4uIF22
5cELSE23
6tELSE24
7aIF34
8nELSE35
9tELSE36
10No letterLoop stops36

The tutorial’s word has no punctuation and uses the stored LetterCount as the loop limit. To let you try cards like “cane...” and “fire-eyed”, this explorer makes a letters-only sequence first and ignores punctuation and hyphens. It uses the five-vowel convention a/e/i/o/u, so y is counted as a consonant here. This extension is stated explicitly; punctuation is not treated as a consonant.

The loop condition uses ≤, so the ninth letter is processed. After the final update, i becomes 10 and the test fails. At every step, Vcount + Ccount equals the number of letters already processed. The procedure returns two values in order: (vowels, consonants). The caller can store them as (V, C) = CountVowelsAndConsonants(X).

Try it yourself

What goes wrong if i increases only inside the vowel branch?

Show explained answer

At the first consonant, i would stay unchanged. The loop would keep processing the same letter forever. Increase i after either branch.

Try it yourself

Why does i < 9 miss information for reluctant?

Show explained answer

It stops before position 9, so the final t is skipped. Use i ≤ 9 for 1-based positions.

Try it yourself

What is returned for reluctant, and what does 6 represent?

Show explained answer

(3, 6): 3 vowels and 6 consonants. Return order is part of the procedure contract.

Try it yourself

What is returned for cane... in the letters-only explorer?

Show explained answer

(2, 2). The letters are c, a, n, e. Dots are ignored rather than counted as consonants.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑