Programming Basics (Pseudocode Tracing)

The following program has a condition inside a nested loop. What is the value of c after it runs?

integer: c ← 0
for (i from 1 to 4 step 1)
  for (j from 1 to i step 1)
    if (j mod 2 = 1)
      c ← c + 1
    endif
  endfor
endfor
  1. A4
  2. B6
  3. C10
Show answer and explanation

Answer: B. 6

The inner loop runs j = 1 to i and increments c only when j is odd. For i = 1 that is j = 1 (once), for i = 2 j = 1 (once), for i = 3 j = 1, 3 (twice) and for i = 4 j = 1, 3 (twice), for a total of 1 + 1 + 2 + 2 = 6. The inner body runs 1 + 2 + 3 + 4 = 10 times in all, but the condition holds in only 6 of them. This is a basic combination of control structures: a selection inside an iteration.

  • A. This counts even j. j mod 2 = 1 is true when j is odd.
  • B. Correct. 1 + 1 + 2 + 2 = 6 times.
  • C. This ignores the if condition and counts all 1 + 2 + 3 + 4 inner passes.
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 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?
  2. Array indices start at 1. The following program looks for the largest element. What is the value of m after it runs?
  3. The following program was meant to reverse the elements of array a. Array indices start at 1. What does a contain after it runs?
  4. Array indices start at 1. What does array a contain after the following program runs?
  5. Array indices start at 1. The following program compares adjacent elements. What is the value of c after it runs?