IPA IP 2023 Question 64

A question IPA Japan published in 令和5年度 ITパスポート試験 公開問題 問64, translated into English. ITPEC is based on the same exams.

The function sigma receives a positive integer as the argument max, and returns the sum of the integers from 1 to max as the return value. Which of the following is the appropriate piece of code to be inserted into A in the program?

[Program]
○ integer: sigma(integer: max)
integer: calcX ← 0
integer: n
for (increase n from 1 to max by 1)
A
endfor
return calcX

Explanation

calcX ← calcX + n — the loop variable n runs through 1, 2, …, max, so adding it to the running total each time gives the sum.

calcX starts at 0. With max = 4 and option (c):

ncalcX after the line
10 + 1 = 1
21 + 2 = 3
33 + 3 = 6
46 + 4 = 10

The function returns 10, which is 1 + 2 + 3 + 4.

Answer (c)

Why not others:

  • •(a) calcX ← calcX × n — multiplies instead of adds, and since calcX starts at 0 it stays 0 for every max; even starting from 1 it would compute the factorial, not the sum
  • •(b) calcX ← calcX + 1 — adds 1 per pass, so it counts the passes and returns max itself
  • •(d) calcX ← n — overwrites the total each pass, so it returns only the last value, max

Key rule: To total values in a loop, start the accumulator at 0 and add the current value to it each pass; to multiply them, start at 1.

Algorithm and Programming · 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.