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
  1. A13
  2. B31
  3. 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.
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. 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?
  2. 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?
  3. The following program passes values along three variables. What are the values of a, b and c after it runs?
  4. The following program repeatedly multiplies x by 3. What is the value of n after it runs?
  5. The following for loop increases i by 2. What is the value of s after it runs?