IPA FE Subject B first sample Question 2

A question IPA Japan published in 基本情報技術者試験 科目Bのサンプル問題 問2, translated into English. ITPEC is based on the same exams.

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 following program reverses the order of the elements of the integer-type array array.

[Program]
integer []: array ← {1, 2, 3, 4, 5}
integer: right, left
integer: tmp
for (increase left from 1 to (the quotient of the number of elements in array ÷ 2) by 1)
right ← A
tmp ← array[right]
array[right] ← array[left]
B ← tmp
endfor

Answer group

OptionAB

Explanation

A: the number of elements in array − left + 1, B: array[left] — each element left is swapped with its mirror, the element left places from the end.

With 5 elements the loop runs for left = 1 and 2, the quotient of 5 ÷ 2; the middle element stays where it is. Element 1 must pair with element 5 and element 2 with element 4, so right = 5 - left + 1. The three lines after it are a swap through tmp: tmp saves array[right], array[right] takes array[left], and the saved value must go into array[left].

leftrightarray after the pass
15{5, 2, 3, 4, 1}
24{5, 4, 3, 2, 1}

Run with each option on {1, 2, 3, 4, 5} and on six elements, only (c) reversed the array.

Answer (c)

Why not others:

  • •(a) — right = 5 - left pairs element 1 with 4 and 2 with 3, one place short of the mirror: the result is {4, 3, 2, 1, 5}
  • •(b) and (d) — array[right] ← tmp writes back the value just saved from array[right], so array[left] never changes and the array ends as it began, {1, 2, 3, 4, 5}

Key rule: In an array of n elements indexed from 1, the mirror of index i is n − i + 1 (check it with i = 1, which must give n); a swap through a temporary variable puts the saved value into the other element.

Array Manipulation · AI-written, may contain errors

This question comes from the past questions IPA Japan publishes, translated into English by ITPEC Practice. ITPEC Practice is an independent study tool and is not affiliated with IPA or ITPEC. See the original paper (PDF) or Report an issue.