ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer cnt = 0
Procedure go(Integer i, Integer s)
    if (s == 10)
        cnt = cnt + 1
        return
    end if
    if (i > 6 OR s > 10)
        return
    end if
    go(i + 1, s + i)
    go(i + 1, s)
End Procedure
go(1, 0)
Print cnt
  1. A. 4
  2. B. 6
  3. C. 7
  4. D. 5

Correct answer: D. 5

go either takes i or skips it, so cnt counts subsets of {1, …, 6} with sum 10 (the check s == 10 comes first, so a subset is counted as soon as it reaches 10): {4, 6}, {1, 3, 6}, {1, 4, 5}, {2, 3, 5}, {1, 2, 3, 4}. cnt = 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic