ITPEC FE Subject B October 2024 Question 3

From the answer group below, select the correct combination of answers to be inserted into A and B in the program. Here, the array index starts at 1.

The program determines the second-largest element of an integer-type array and outputs its value. For instance, the second largest element of the array {2, 6, 9, 1, 7, 5} is 7. Here, we assume that the array has two or more elements and that no duplicate elements are present in the array.

[Program]
integer []: array ← {2, 6, 9, 1, 7, 5}
integer: i
integer: max1 ← -∞
integer: max2 ← -∞
for (increase i from 1
to the number of elements of array by 1)
if (A)
max2 ← max1
max1 ← array[i]
elseif (array[i] > max2)
B
endif
endfor
output max2

Answer group

OptionAB

Explanation

A: array[i] > max1, B: max2 ← array[i] — a new maximum pushes the old one down to second place, and a value between the two replaces only the second.

Trace with {2, 6, 9, 1, 7, 5}:

iarray[i]branchmax1max2
12if2-∞
26if62
39if96
41neither96
57elseif97
65neither97

The output is 7, as the question states.

Answer (f)

Why not others:

  • •(a) and (b) — array[i] < max1 enters the promotion branch for a smaller value; tracing either version outputs 9, the largest element, instead of 7
  • •(c) and (d) — array[i] < max2 demotes on small values: (c) outputs -∞, because nothing is less than -∞ and max2 is never set, and (d) outputs 1
  • •(e) — A is right, but B overwrites max1 with 7 when 7 only beats max2; max2 stays 6 and 6 is output
  • •(g) and (h) — with A as array[i] > max2 the elseif repeats the same test, so B is unreachable; at 7, which beats max2 (6), the old maximum 9 is demoted into max2 and 9 is output

Key rule: When tracking the two largest values, compare with the larger one first, and in that branch shift the old maximum down before overwriting it.

Array Manipulation · AI-written, may contain errors

This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.