Programming fundamentals - OCRCondition-controlled iteration

Programs are designed using common building blocks, known as programming constructs. These programming constructs form the basis for all programs.

Part ofComputer ScienceComputational thinking, algorithms and programming

Condition-controlled iteration

Condition-controlled iteration repeatedly a section of code until a condition is met - or no longer met. There are two types of condition-controlled iteration:

  • while loops - uses the statements while and endwhile
  • repeat loops - uses the statements repeat and until

While condition-controlled loops

While loops test the condition at the beginning of the . If the condition is met, the code within the loop is executed before the loops back to test the condition again. This program would print out a message six times:

count = 0
while count < 6 print(“Coding is cool”) count = count + 1
endwhile

The while statement defines the start of the loop. The endwhile statement declares the end of the loop. A , in this case count, is used for the condition. The while statement also tests the condition, in this case to see if the value of count is less than six. 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 which 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 program:

count = 6
while count < 6 print(“Coding is cool”) count = count + 1
endwhile

The first time the condition is tested, the result will be FALSE as the value of count is not less than six. 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:

count = 0
repeat print(“Coding is cool”) count = count + 1
until count = 10

The 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.