Counting vowels — Pseudocode Aptitude Question
Counting vowels: Characters are numbered from 1, so s[1] is the first character. What does this print? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
Characters are numbered from 1, so s[1] is the first character. What does this print?
String s
Integer i, c
Set s = "PSEUDOCODE"
Set c = 0
For i = 1 to length(s)
If s[i] is one of A, E, I, O, U Then
Set c = c + 1
End If
End For
Print cOptions
- 3
- 4
- 5
- 6
Show the answer and the worked solution
Correct answer: C. 5
Worked solution
- The word is P S E U D O C O D E, ten characters long.
- The vowels sit at positions 3 (E), 4 (U), 6 (O), 8 (O) and 10 (E).
- That is 5 vowels, so c = 5 is printed.
Answer: 5.
The idea
String traversal questions are won by writing the string out with its positions underneath. Counting in your head is where the off-by-one creeps in.
Shortcut. Count the consonants instead: P, S, D, C, D are 5 of the 10 letters, so the other 5 are vowels.
Common trap. 3 counts only the distinct vowels E, U and O; the repeated O and E each pass the test again and add to c.