ProgrammingHardGoldman Sachs OA · Amazon OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
// circular list of 6 people: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> back to 1
Node p = node 1
while (p.next != p)
    p.next = p.next.next        // remove the person after p
    p = p.next
end while
Print p.value
  1. A. 1
  2. B. 5
  3. C. 3
  4. D. 6

Correct answer: B. 5

Every second person is removed: 2, 4, 6, then 3, then 1, leaving 5 (the Josephus survivor for n = 6, k = 2: 2 × (6 − 4) + 1 = 5).

More Pseudocode and Code Tracing questions

Exams that ask this topic