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
- A9
- B10
- 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.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions