Loops (or iterations) are steps that are repeated a number of times in an algorithm. They make algorithms simpler because they don’t need to include groups of unnecessary steps.
For example, the steps involved in eating breakfast could be:
Eat spoonful of cereal and milk
........continue these steps until bowl is finished (could be a large number of steps)
End
This algorithm could be rewritten using a loop:
When writing algorithms in pseudocode we can use a WHILE loop. A while loop states a condition at the start of the loop which determines how many times a loop is repeated in an algorithm.
Look at this algorithm written in pseudocode, and the explanation of each line of code
START |
start |
SET a = 2 |
give the variable a , the value 2 |
SET sum = 0 |
give the variable sum , the value 0 |
WHILE a < 5 |
while a has a value less than 5 repeat the next 2 steps |
sum = sum + a |
add a to the value of sum |
a = a + 1 |
add 1 to the value of a |
END WHILE |
stop the loop when a is no longer less than 5 |
PRINT sum |
print the final value of sum |
END |
end |
This loop contains 2 steps sum = sum + a
a = a + 1
these will be repeated until a
is no longer less than 5
. The values of the variables a
and sum
for each loop are:
sum |
a |
|
initially | $0$0 | $2$2 |
after first loop | $0+2=2$0+2=2 | $2+1=3$2+1=3 |
after second loop | $2+3=5$2+3=5 | $3+1=4$3+1=4 |
after third loop | $5+4=9$5+4=9 | $4+1=5$4+1=5 |
At the end of the third loop the value of a
is 5
and so the condition for the loop to end has been reached. The final value of sum
is 9
. This is the value that will be printed (OUTPUT
) from the algorithm.
Look at the pseudocode below:
START
SET a = 2
SET sum = 0
WHILE a < 9
sum = sum + a
a = a + 1
END WHILE
PRINT sum
END
The initial value of a
is $\editable{}$.
What is the OUTPUT
of this code?
OUTPUT:
$\editable{}$
Consider the algorithm represented by the flow chart:
Rearrange the letters $A$A, $B$B, $C$C, $D$D, $E$E, $F$F and $G$G so the corresponding pseudocode correctly represents the flow chart's algorithm.
$C$C: a = a + 1 |
$E$E: SET a = 1 |
$A$A: WHILE a ≠ 5 |
$F$F: PRINT sum |
$B$B: sum = sum + a |
$G$G: END WHILE |
$D$D: SET sum = 0 |
START |
|
Line 1 | $\editable{}$ |
Line 2 | $\editable{}$ |
Line 3 | $\editable{}$ |
Line 4 | $\editable{}$ |
Line 5 | $\editable{}$ |
Line 6 | $\editable{}$ |
Line 7 | $\editable{}$ |
END |
Look at the pseudocode below:
Note that the symbol <
represents the statement 'less than'.
START SET a = 2 WHILE a < 10 PRINT a
a = a + 2
END WHILE END
What is the OUTPUT
of this code? Write each value on the same line, separated by a comma.
OUTPUT:
$\editable{}$