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.
Answer group
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}:
The output is 7, as the question states.
Answer (f)
Why not others:
- •(a) and (b) —
array[i] < max1enters the promotion branch for a smaller value; tracing either version outputs 9, the largest element, instead of 7 - •(c) and (d) —
array[i] < max2demotes on small values: (c) outputs -∞, because nothing is less than -∞ andmax2is never set, and (d) outputs 1 - •(e) — A is right, but B overwrites
max1with 7 when 7 only beatsmax2;max2stays 6 and 6 is output - •(g) and (h) — with A as
array[i] > max2theelseifrepeats the same test, so B is unreachable; at 7, which beatsmax2(6), the old maximum 9 is demoted intomax2and 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.