ProgrammingVery hardInfosys · Capgemini pattern

This function uses a counter that PERSISTS across calls (a static/global variable), starting at 1. 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 1. What does each of the 4 calls print, in order?
Integer counter = 1  // 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. 3, 7, 15, 31
  2. B. 3, 3, 3, 3
  3. C. 2, 6, 14, 30
  4. D. 31, 15, 7, 3

Correct answer: A. 3, 7, 15, 31

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

More Pseudocode and Code Tracing questions

Exams that ask this topic