ITPEC FE Subject B October 2025 Question 12
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 function containsSubstring receives two-character arrays str and seq as arguments, and returns a boolean value indicating whether the character array str contains the sequence seq as a substring. The character array str contains seq as a substring if every sequence of consecutive characters in seq exists somewhere in the sequence of characters in str, in the same order. For example, containsSubstring( returns true, and containsSubstring( returns false. Assume that the number of elements in str and seq is one or more.
Answer group
Explanation
A: str[i + j - 1], B: j = seqlen + 1 — line up character j of seq with position i + j - 1 of str, and report a match only when the while loop ran past its last character.
i is the position in str where a candidate substring starts, from 1 to len = strlen - seqlen + 1, the last start that still fits. Character j of seq must therefore be compared with str at i + j - 1: for j = 1 that is str[i] itself, and at the last start with j = seqlen it is str[strlen], the final element.
The while loop ends in one of two ways. A mismatch exits the block with j still ≤ seqlen. If every character matches, j is incremented once more after the last comparison, and the loop ends with j = seqlen + 1. Only that value proves a full match.
Trace containsSubstring(, where len = 3. At i = 1, "a" ≠ "p", exit with j = 1. At i = 2, "p" matches, then str[3] = "p" ≠ "l", exit with j = 2. At i = 3, "p", "l" and "e" all match, j reaches 4 = seqlen + 1, and the function returns true.
Answer (e)
Why not others:
- •(a), (b) and (c) —
str[is shifted one place right:i + j] str[1]is never compared, and at i =len, j =seqlenit readsstr[, past the end of the arraystrlen + 1] - •(d) —
j = seqlenis also what a mismatch on the last character leaves. Forseq={"a", "e"}: at i = 1, "a" matches, then "p" ≠ "e" exits with j = 2 =seqlen, so it returnstruewhere the question saysfalse - •(f) —
j = seqlen - 1is left by a mismatch on the second-to-last character, and a full match never satisfies it. Forseq={"a", "e"}it returnstrueat i = 2, where "p" ≠ "a" exits with j = 1
Key rule: When a loop can end either by a break or by its own condition, test the loop variable for the value only the natural exit leaves (bound + 1), and check window indexes at both ends of their range.
String Processing · 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.