ProgrammingHardTCS NQT · Infosys · Capgemini

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer val[6] = {5, 8, 2, 9, 4, 7}
Integer nxt[6] = {3, 5, 0, 1, -1, 4}
Integer p = 2, s = 0, k = 0
While p != -1
    If k mod 2 = 0 Then
        s = s + val[p]
    Else
        s = s - val[p]
    End If
    p = nxt[p]
    k = k + 1
End While
Print s, k
  1. A. -1 6
  2. B. 1 6
  3. C. 5 6
  4. D. 1 5

Correct answer: B. 1 6

The chain from index 2 is 2 -> 0 -> 3 -> 1 -> 5 -> 4 -> end (6 nodes). With alternating signs: +2 - 5 + 9 - 8 + 7 - 4 = 1, and k counts 6 visited nodes.

More Pseudocode and Code Tracing questions

Exams that ask this topic