Programming Basics (Pseudocode Tracing)

The following for loop increases its control variable by 5. What is the value of c after it runs?

integer: c ← 0
for (i from 10 to 50 step 5)
  c ← c + 1
endfor
  1. A8
  2. B9
  3. C10
Show answer and explanation

Answer: B. 9

i takes the values 10, 15, 20, 25, 30, 35, 40, 45 and 50; the next value 55 exceeds the final value 50, so the loop ends. (50 − 10) ÷ 5 = 8 is the number of intervals between them, and the number of values including both ends, 10 and 50, is 8 + 1 = 9, so the body runs 9 times. As with fence posts, confusing the number of intervals with the number of points causes an off-by-one error.

  • A. This is the number of intervals, (50 − 10) ÷ 5 = 8, and misses the pass for i = 10.
  • B. Correct. The body runs for the nine values from 10 to 50 in steps of 5.
  • C. This is 50 ÷ 5 = 10, the count if i started at 5.
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. In the following program, and does not evaluate its right side when the left side is false (short-circuit evaluation). cnt is a global variable. What is the value of cnt after the program runs?
  2. The following program searches the n-element array a for the value x and stores the index where it is found in i. Array indices start at 1. and and or do not evaluate their right side when the left side alone decides the result. Which condition in 【a】 reads a[n + 1], outside the array, when x is not in a?
  3. 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?
  4. 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?
  5. 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?