ITPEC FE Subject B April 2025 Question 12

From the answer group below, select the correct answer to be inserted into blank in the program. Here, the array index starts at 1.

The function hammingDistance compares the two-character arrays s1 and s2 that are given as arguments. s1 and s2 have one or more elements. If s1 and s2 do not have the same number of elements, the function returns -1. Otherwise, it returns the number of indices where two arrays have different element values at the same index. The figure shows an example of two character arrays. APPLE and APRIE have different element values at two indices.

APPLEAPRIE

Figure Example of two-character arrays

The table lists examples of s1 and s2 given to the function hammingDistance and the return values. In the program, areas outside of the arrays must not be referenced.

Table Examples of s1 and s2 given to the function hammingDistance and the return values

s1s2Return value
{"a", "p", "p", "l", "e"}{"a", "p", "p", "l", "e"}0
{"a", "p", "p", "l", "e"}{"a", "p", "r", "i", "l"}3
{"a", "p", "p", "l", "e"}{"m", "e", "l", "o", "n"}5
{"a", "p", "p", "l", "e"}{"p", "i", "e"}-1
[Program]
○ integer: hammingDistance(character []: s1, character []: s2)
integer: i, cnt ← 0
if (the number of elements in s1 ≠ the number of elements in s2)
return -1
endif
for (increase i from 1 to the number of elements in s1 by 1)
if (blank)
cnt ← cnt + 1
endif
endfor
return cnt

Answer group

Explanation

s1[i] ≠ s2[i] — the loop variable i walks both arrays in step, and cnt must grow only where the characters at the same index differ.

After the length check both arrays have the same number of elements, so i from 1 to that number stays inside both of them. cnt is the result, not a position: it starts at 0 and increases only on a mismatch. Checking against the table:

  • •apple and apple: no index differs, 0
  • •apple and april: indices 3, 4 and 5 differ (p/r, l/i, e/l), 3
  • •apple and melon: all five indices differ, 5

Answer (h)

Why not others:

  • •(a), (b), (c) and (d) — index s1 with cnt, which is 0 on the first pass: s1[0] lies outside an array whose index starts at 1, which the description forbids, and cnt does not advance with the loop anyway
  • •(e) and (f) — the same fault on the other side: s2[cnt] reads s2[0] first, and later compares s1[i] with an unrelated position
  • •(g) — counts the indices where the characters match, so apple and apple would return 5 instead of 0

Key rule: In a position-by-position comparison, index both arrays with the loop variable; a counter that changes only conditionally is not a position.

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.