Iteration

<< Previous: Selection Next: Nesting >>

About iteration

Iteration, sometimes called looping,is where code is executed more than once. There are three types of loop you need to be familiar with:
- For loops
- While loops
- Repeat until loops
We will now look at each of these in more detail.

For loops

For loops are known as definite iteration, also sometimes referred to as count-controlled iteration. This is because in a for loop we know how many times the loop will run. A variable is established that works as a counter during the execution of the loop. Although it may behave differently in different languages, in pseudocode we take the range vaues as being literal and inclusive. In the example below the temporary variable attempts which acts as a counter would first hold the value 1 and then next time through the loop it would be 2 and finally 3.

While loops

While loops are known as indefinite iteration, also sometimes referred to as condition-controlled iteration. This is because in a while loop we don't know how many times the loop will run. Before the loop runs and after each execution of the loop, the condition is checked again. If it is true, the code in the loop runs again. If not the loop is finished and the program moves on to the next line of code. One of the common mistakes that can be made is to not give the opportunity for the result of the condition to check. In the example below if the user could not have the chance to enter a new guess then the code would run forever. This is known as an infinite loop and will cause a program to crash.

Repeat until loops

Repeat until loops are another form of indefinite iteration, also sometimes referred to as condition-controlled iteration. This is because in a repeat loop we don't know how many times the loop will run. A repeat until loop will always execute at least once because the condition is not checked until the end. This is its main difference from the while loop. After each execution of the loop, the condition is checked again. If it is true, the code in the loop runs again. If not the loop is finished and the program moves on to the next line of code. There are some situations where it is better to use while and some where repeat until will be better. A straight swap into our last algorithm doesn't work because if the user was right on the first guess they would be told they were wrong. However as you can see it is possible to make an effective algorithm to do th same using repeat until.



Knowledge check


Questions:
Correct:

Question text


<< Previous: Selection Next: Nesting >>

© All materials created by and copyright S.Goff