Skip to content

平成22年度 秋期 ITパスポート試験 問69

This question's explanation and your answers so far.

問69
頻出度★★☆

二つの変数 x と y に対して,次の手続を (1) から順に実行する。処理が終了したとき,x の値は幾らになるか。 〔手続〕 (1) x に 2 を代入し,y に 3 を代入する。 (2) y の値から 1 を引いたものを y に代入する。 (3) x の値と y の値を加えたものを x に代入する。 (4) y≠1 なら手続 (2) に戻り,y=1 なら処理を終了する。

出典 平成22年度 秋期 ITパスポート試験 問69
解説

問 69

  • Incorrectア

    4 is an intermediate value: the state at the end of the first pass (x=4, y=2). At that point y=2 is not 1, so the test in (4) sends the flow back to procedure (2) and one more pass is carried out. If you stop after a single pass without checking the loop-ending condition y=1, you end up choosing 4.

  • イ

    正解 This question is solved simply by tracing the procedure line by line. After (1), x=2 and y=3. [1st pass] In (2) y becomes 3-1=2, in (3) x becomes 2+2=4, and in (4) y=2 is not 1, so the flow returns to (2). [2nd pass] In (2) y becomes 2-1=1, in (3) x becomes 4+1=5, and in (4) y=1, so the processing ends. The value of x at the end is 5, so the correct answer is “イ”. The key point is that the test in (4) comes after (3), so the loop runs twice until y becomes 1, and the two values y=2 and y=1 are added to x in turn. Written as a table, [x, y] changes as (2,3) → (4,2) → (5,1).

  • Incorrectウ

    7 is the value you get if the order of procedures (2) and (3) is mixed up, adding first and only then decreasing y. With that wrong order: x=2+3=5, y=2 → x=5+2=7, y=1 and the processing ends, giving 7. In the actual procedure each pass “subtracts 1 from y first, then adds”, so the values of y added to x are not 3 but 2 and 1.

  • Incorrectエ

    8 is the value you get if the initial value y=3 is also included in the additions (2+3+2+1=8). Procedure (3) is always executed after (2) has subtracted 1 from y, so there is never a chance for y to be added while it is still 3. Only two additions are made to x: y=2 and y=1.

ここがポイント
  • For iteration (loop) questions, the surest approach is to build a table and trace how each variable changes line by line. Here, following [x, y] = (2,3) → (4,2) → (5,1) gives you the answer.
  • Pay attention to where the ending condition is tested. Because the test (4) comes after the operations (2) and (3), the body is always executed at least once and repeats until the condition y=1 holds (a post-test loop). Also keep in mind the basics of assignment: the right-hand side is evaluated first, then the variable on the left is overwritten.
用語

Your answers