Programming Basics (Pseudocode Tracing)

Array indices start at 1. The following program compares adjacent elements. What is the value of c after it runs?

integer array: a ← {2, 2, 3, 3, 3, 1, 1}
integer: c ← 0
for (i from 1 to length(a) − 1 step 1)
  if (a[i] = a[i + 1])
    c ← c + 1
  endif
endfor
  1. A4
  2. B6
  3. C7
Show answer and explanation

Answer: A. 4

The program counts pairs of adjacent elements that are equal. i runs from 1 to 6, and four pairs are equal: a[1] and a[2], a[3] and a[4], a[4] and a[5], and a[6] and a[7], so c = 4. There are 7 − 1 = 6 comparisons. The final value is length − 1 so that a[i + 1] stays within the array.

  • A. Correct. The equal pairs are (2, 2), (3, 3), (3, 3) and (1, 1).
  • B. This is the number of comparisons. c increases only for equal pairs.
  • C. This is the number of elements that equal a neighbor. The program counts adjacent pairs, not elements.
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. m[i, j] is the element in row i, column j of the 2D array m, and indices start at 1. What is the value of s after the following program runs?
  2. The following program copies the elements of the 2D array m with 4 rows and 5 columns into the 20-element array b. m[i, j] is the element in row i, column j, and indices start at 1. At which index of b is m[3, 2] stored?
  3. Array indices start at 1, and + concatenates strings. What is the value of r after the following program runs?
  4. The following function isPal returns true if the characters in the string array s read the same forward and backward (a palindrome). Array indices start at 1. What should replace 【a】 in the program?
  5. ÷ is division; when the result is assigned to an integer variable (including a function argument), the fractional part is discarded. What does the following function f return when called as f(9087)?