Programming Basics (Pseudocode Tracing)
Class Counter gives each instance its own integer member variable count (0 when created), and its method inc() adds 1 to its own count. What is the value of x after the following program runs?
Counter: c1 ← new Counter()
Counter: c2 ← new Counter()
c1.inc()
c1.inc()
c2.inc()
c1.inc()
integer: x ← c1.count × 10 + c2.count
- A13
- B31
- C44
Show answer and explanation
Answer: B. 31
In object-oriented programming, new Counter() creates a new instance each time, so c1 and c2 each have their own count. c1.inc() increments only c1's count, so c1.count = 3 and c2.count = 1. x = 3 × 10 + 1 = 31. Member variable values are kept separately for each instance.
- A. This mixes up the counts of c1 and c2.
- B. Correct. c1.count = 3 and c2.count = 1.
- C. This assumes count is shared by all instances. Each instance has its own member variables.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions