Skip to content

令和5年度 ITパスポート試験 問64

This question's explanation and your answers so far.

問64
頻出度★★☆

関数 sigma は, 正の整数を引数 max で受け取り, 1から max までの整数の総和を戻り値とする。プログラム中の a に入れる字句として, 適切なものはどれか。 〔プログラム〕 ○整数型: sigma(整数型: max) 整数型: calcX ← 0 整数型: n for (n を 1 から max まで 1 ずつ増やす) a endfor return calcX

出典 令和5年度 ITパスポート試験 問64
解説

問 64

  • Incorrectア

    「calcX ← calcX × n」 is multiplication. Since calcX starts at 0, no matter how many times you multiply, calcX stays 0 and you never get the sum (to obtain a product you would need to start at 1). Wrong.

  • Incorrectイ

    「calcX ← calcX + 1」 adds only 1 each time. Since 1 is added once per iteration, the result becomes max (the number of iterations), not the sum 1+2+…+max. Wrong.

  • ウ

    正解 The function sigma returns the sum of the integers from 1 to max. calcX is initialized to 0, and the for loop repeats while increasing n from 1 to max by 1. To obtain the sum, you simply add the current n to the accumulator variable calcX in each iteration. If you put 「calcX ← calcX + n」 at a, calcX progresses as 0 →1 →1+2 →1+2+3 →…, and at the end of the loop it becomes the sum 1+2+…+max. Therefore the correct answer is ウ.

  • Incorrectエ

    「calcX ← n」 is assignment, not addition. Since calcX is overwritten with n each time, only the last value max remains at the end of the loop, so you never get the sum. Wrong.

ここがポイント
  • The basic pattern for computing a sum with iteration (a for loop) is to initialize an accumulator variable to 0 and keep adding inside the loop as 「accumulator ← accumulator + loop variable」.
  • Distinguish a sum (addition) from a product (multiplication): for a sum, initialize the accumulator to 0 and use the operator “+”; for a product, initialize to 1 and use “×”. Also note the difference between plain assignment 「←」 and accumulating addition 「← …+…」.
用語

Your answers