ProgrammingHardTCS NQT · Infosys · Capgemini pattern

This function uses a counter that PERSISTS across calls (a static/global variable), starting at 5. What does each of the 4 calls print, in order?

This function uses a counter that PERSISTS across calls (a static/global variable), starting at 5. What does each of the 4 calls print, in order?
Integer counter = 5  // static: keeps its value between calls
Function next()
    counter = counter * 2 + 1
    Print counter
end Function

// next() is called 4 times in a row
  1. A. 11, 23, 47, 95
  2. B. 11, 11, 11, 11
  3. C. 10, 22, 46, 94
  4. D. 95, 47, 23, 11

Correct answer: A. 11, 23, 47, 95

Because counter is static, each call updates the SAME variable left over from the previous call, not a fresh copy reset to 5. Tracing counter = 5 through 4 updates of counter = counter*2+1 gives, in order, 11, 23, 47, 95. Resetting to 5 every call would wrongly give 11, 11, 11, 11 every time.

More Pseudocode and Code Tracing questions

Exams that ask this topic