Programming Basics (Pseudocode Tracing)

Real values are represented in IEEE 754 double precision (binary64), and each sum is rounded to the nearest representable value. What is the value of c after the following program runs?

real: x ← 0.0
integer: c ← 0
while (x < 1.0)
  x ← x + 0.1
  c ← c + 1
endwhile
  1. A9
  2. B10
  3. C11
Show answer and explanation

Answer: C. 11

0.1 is a repeating fraction in binary, and in double precision it is stored as an approximation slightly larger than 0.1. Each addition adds a rounding error, and the result of adding it 10 times is not 1.0 but 0.9999999999999999. This value satisfies x < 1.0, so an 11th addition is made, x becomes about 1.1 and the loop ends, giving c = 11. Count loop iterations with an integer variable, and avoid comparing real numbers with = or ≠. With the condition x ≠ 1.0, x never equals exactly 1.0 and the loop never ends.

  • A. After 9 additions the value is about 0.9, still below 1.0.
  • B. Without errors x would be 1.0 after 10 additions, but the actual 10th result is slightly below 1.0.
  • C. Correct. The sum after 10 additions is 0.9999999999999999, below 1.0, so the body runs 11 times.
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. What is the value of x after the following program runs?
  2. 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?
  3. 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?
  4. The following program passes values along three variables. What are the values of a, b and c after it runs?
  5. The following program repeatedly multiplies x by 3. What is the value of n after it runs?