ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer total = 0, n = 5
for (each i from 1 to n)
    for (each j from i to n)
        total = total + 1
    end for
end for
Print total
  1. A. 25
  2. B. 10
  3. C. 20
  4. D. 15

Correct answer: D. 15

For each i, j runs from i to n, giving n-i+1 iterations: i=1 gives 5, i=2 gives 4, i=3 gives 3, i=4 gives 2, i=5 gives 1. Total 5+4+3+2+1=15.

More Pseudocode and Code Tracing questions

Exams that ask this topic