AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easyfor loopaccumulator

~60s

Adding the even numbers

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 total
Show the answer and the worked solution

Correct answer: C.

30

Worked solution

  1. The loop visits i = 1 to 10, but the guard i MOD 2 == 0 admits only the even values.
  2. Those are 2, 4, 6, 8 and 10.
  3. 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.

Adding the even numbers — Pseudocode Aptitude Question

Adding the even numbers: What does the following pseudocode print? Answer and worked solution on CodeKairo.

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 total

Options

  1. 20
  2. 25
  3. 30
  4. 55
Show the answer and the worked solution

Correct answer: C. 30

Worked solution

  1. The loop visits i = 1 to 10, but the guard i MOD 2 == 0 admits only the even values.
  2. Those are 2, 4, 6, 8 and 10.
  3. 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.

All Pseudocode questions · placement mock tests