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. A variable of type Counter holds a reference to an instance, not the instance itself. What is the value of x after the following program runs?
Counter: c1 ← new Counter()
Counter: c2 ← c1
c1.inc()
c2.inc()
c2 ← new Counter()
c2.inc()
integer: x ← c1.count × 10 + c2.count
- A11
- B21
- C33
Show answer and explanation
Answer: B. 21
c2 ← c1 copies only the reference, so c1 and c2 point to the same instance. c1.inc() and c2.inc() therefore increment the same count, and c1.count becomes 2. The next c2 ← new Counter() makes c2 point to a new instance, and the following c2.inc() sets only the new count to 1. x = 2 × 10 + 1 = 21.
- A. This assumes c2 ← c1 copies the instance. In fact both point to the same instance.
- B. Correct. c1.count = 2, and the new instance has c2.count = 1.
- C. This assumes c2 still points to the same instance as c1 after c2 ← new Counter().
Continue: 9 more Programming Basics (Pseudocode Tracing) questions