Condition-controlled iteration
Condition-controlled iterationThe repetition of a block of statements within a computer program. repeatedly executionThe process of a program being run on a computer. a section of code until a condition is met - or no longer met. The two most common types of condition-controlled iteration are:
- while loops, which use the statements
WHILEandEND WHILE - repeat loops, which use the statements
REPEATandUNTIL
While condition-controlled loops
While loops test the condition at the beginning of the loopingRepeatedly executing a section of code.. If the condition is met, the code within the loop is executed before the program loops back to test the condition again. This pseudocode Also written as pseudo-code. A method of writing up a set of instructions for a computer program using plain English. This is a good way of planning a program before coding. program would print out a message six times.
SET count TO 0 WHILE count < 6 DO SEND ‘Coding is cool’ TO DISPLAY SET count TO count + 1 END WHILEThe WHILE statement defines the start of the loop. The END WHILE statement declares the end of the loop. A variableA memory location within a computer program where values are stored. - in this case count - is used for the condition and it must be initialised before the loop starts. The WHILE statement tests the condition - in this case to see if the value of count is less than 6. If the result is TRUE, the code within the loop is executed. Then the program loops back to the condition, which is tested again.
The iteration continues until the condition test result is FALSE. At this point the loop ends and the program executes the next line of code in sequence after the loop.
Because the condition is tested at the start of the loop, it is possible for the code within it to never actually be executed. Consider this pseudo-code program:
SET count TO 6 WHILE count < 6 DO SEND ‘Coding is cool’ TO DISPLAY SET count TO count + 1 END WHILEThe first time the condition is tested, the result will be FALSE as the value of count is not less than 6. Because of this, none of the code within the loop will be executed and the program will move onto the next line of code in sequence after the loop.
Repeat condition-controlled loops
Repeat loops function in the same way as while loops with one major difference - the condition is tested at the end of the loop.
SET count TO 0 REPEAT SEND ‘Coding is cool’ TO DISPLAY SET count TO count + 1 UNTIL count = 10The REPEAT statement defines the start of the loop. The UNTIL statement tests the condition. Because the condition is tested at the end, the code within the loop is always executed at least once, even if the result of the test is FALSE. REPEAT loops are often used to display menus that always need to be displayed at least once.