Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
This algorithm outputs the even numbers from to .
FOR Number ← 2 TO 12 STEP 2
OUTPUT Number
NEXT NumberAmend it so that it outputs the same numbers in the opposite order, from down to . How many numbers does the amended algorithm output?
Cambridge pseudocode: keywords in capitals, names in mixed case, ← for assignment, INPUT and OUTPUT, IF ... THEN ... ELSE ... ENDIF, CASE OF ... OTHERWISE ... ENDCASE, FOR ... TO ... STEP ... NEXT, WHILE ... DO ... ENDWHILE, REPEAT ... UNTIL. DIV(a, b) is the whole-number quotient and MOD(a, b) the remainder.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Step 1. The amendment. Start at , finish at , and take away each time.
FOR Number ← 12 TO 2 STEP -2
OUTPUT Number
NEXT NumberStep 2. The count. The values are , , , , , . That is numbers.
Answer: the loop line becomes FOR Number ← 12 TO 2 STEP -2, and it outputs numbers.
Watch out. Changing only the step to -2 and keeping 2 TO 12 gives a loop that never runs. The count starts at and goes down, so it is already past the end value . Both the order of the limits and the sign of the step must change.
Log in to join the discussion.
Loading…