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
  1. A11
  2. B21
  3. 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().
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. The two assignments in the following program were meant to swap the values of x and y. What are the values of x and y after it runs?
  2. The following program passes values along three variables. What are the values of a, b and c after it runs?
  3. The following program repeatedly multiplies x by 3. What is the value of n after it runs?
  4. The following for loop increases i by 2. What is the value of s after it runs?
  5. In the following nested loop, the inner loop starts from the outer variable i. What is the value of c after it runs?