ProgrammingVery hardGoldman Sachs OA · TCS Digital

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 n = 7, c = 1
for (each k from 0 to n - 1)
    Print c
    c = c / (k + 1) * (n - k)
end for
Print c
  1. A. 1 7 21 35 35 21 7 1
  2. B. 1 7 18 30 28 15 4 0
  3. C. 1 7 18 30 28 15 4 1
  4. D. 1 7 21 35 35 21 7 0

Correct answer: B. 1 7 18 30 28 15 4 0

Dividing before multiplying truncates: 7 / 2 = 3 → 3 × 6 = 18 instead of 21, and the error snowballs: 18 / 3 × 5 = 30, 30 / 4 × 4 = 28, 28 / 5 × 3 = 15, 15 / 6 × 2 = 4, 4 / 7 × 1 = 0. The correct row 1 7 21 35 35 21 7 1 needs c × (n − k) / (k + 1).

More Pseudocode and Code Tracing questions

Exams that ask this topic