The function of structural components of programs - EdexcelCondition-controlled iteration

Programs are designed and implemented using common building blocks, known as programming constructs. These constructs are sequence, selection and iteration and they form the basis for all programs.

Part ofComputer ScienceApplication of computational thinking

Condition-controlled iteration

Condition-controlled repeatedly 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 WHILE and END WHILE
  • repeat loops, which use 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 program loops back to test the condition again. This 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 WHILE

The WHILE statement defines the start of the loop. The END WHILE statement declares the end of the loop. A - 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 WHILE

The 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 = 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. REPEAT loops are often used to display menus that always need to be displayed at least once.