ProgrammingVery hardTCS NQT · Accenture pattern

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

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

// next() is called 6 times in a row
  1. A. 255, 127, 63, 31, 15, 7
  2. B. 7, 15, 31, 63, 127, 255
  3. C. 7, 7, 7, 7, 7, 7
  4. D. 6, 14, 30, 62, 126, 254

Correct answer: B. 7, 15, 31, 63, 127, 255

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

More Pseudocode and Code Tracing questions

Exams that ask this topic