Programming Basics (Pseudocode Tracing)

In the following nested loop, the inner loop starts from the outer variable i. What is the value of c after it runs?

integer: c ← 0
for (i from 1 to 5 step 1)
  for (j from i to 5 step 1)
    c ← c + 1
  endfor
endfor
  1. A15
  2. B20
  3. C25
Show answer and explanation

Answer: A. 15

The inner loop runs j from i to 5, so it runs 5 times for i = 1, 4 times for i = 2, …, and once for i = 5. The total is 5 + 4 + 3 + 2 + 1 = 15. Because the inner initial value depends on the outer variable i, the count is not simply 5 × 5.

  • A. Correct. 5 + 4 + 3 + 2 + 1 = 15 times.
  • B. This is the number of tests of the inner for condition. For each i there is one extra test that finds the final value exceeded.
  • C. This assumes the inner loop always runs from 1 to 5: 5 × 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. The following program has a condition inside a nested loop. What is the value of c after it runs?
  2. The following program was meant to compute the sum of all elements of array a. Array indices start at 1. What is the value of s after it runs?
  3. Array indices start at 1. The following program looks for the largest element. What is the value of m after it runs?
  4. The following program was meant to reverse the elements of array a. Array indices start at 1. What does a contain after it runs?
  5. Array indices start at 1. What does array a contain after the following program runs?