Adding the even numbers — Pseudocode Aptitude Question
Adding the even numbers: What does the following pseudocode print? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
What does the following pseudocode print?
Integer i, total
Set total = 0
For i = 1 to 10
If i MOD 2 == 0 Then
Set total = total + i
End If
End For
Print totalOptions
- 20
- 25
- 30
- 55
Show the answer and the worked solution
Correct answer: C. 30
Worked solution
- The loop visits i = 1 to 10, but the guard i MOD 2 == 0 admits only the even values.
- Those are 2, 4, 6, 8 and 10.
- total = 2 + 4 + 6 + 8 + 10 = 30.
Answer: 30.
The idea
A guarded accumulator sums only the values that pass the test, so list the survivors first and add them once. The whole-range sum 55 is the trap for anyone who ignores the If.
Shortcut. The survivors are the first five even numbers, and the sum of the first k evens is k(k + 1): 5 × 6 = 30, with no loop trace needed.
Common trap. 25 is the sum of the odd values 1 + 3 + 5 + 7 + 9, which is what a candidate gets by reading i MOD 2 == 0 as "i is odd" and keeping the numbers that leave remainder 1.