ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode? (All variables are integers, so / is integer division.)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division.)
Integer c = 0, i = 16
while (i > 0)
    for (each j from 1 to i)
        c = c + 1
    end for
    i = i / 2
end while
Print c
  1. A. 80
  2. B. 30
  3. C. 31
  4. D. 16

Correct answer: C. 31

The inner loop runs 16 + 8 + 4 + 2 + 1 = 31 times (i = 1 still runs once, then 1 / 2 = 0 ends the loop). This geometric pattern is O(n), not O(n log n). 16 × 5 = 80 is the trap.

More Pseudocode and Code Tracing questions

Exams that ask this topic