Conditions and counters
A conditionIn computing, this is a statement or sum that is either true or false. A computation depends on whether a condition equates to true or false. is something checked every time a loop runs. A counter keeps track of how many times something is done. Both a condition and a counter are used to perform an iteration.
For example, a person wants to clean their teeth. Most people have 32 teeth. Each step in the algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. could be written as:
- Clean tooth 1
- Clean tooth 2
- Clean tooth 3... and so on, up to 32.
But that would be very repetitive. Instead, iteration could be used to repeat the steps:
- Put toothpaste on the toothbrush.
- Set teeth cleaned counter to 0.
- Start cleaning a tooth.
- After cleaning a tooth, increase the teeth cleaned counter by 1.
- Check the teeth cleaned counter. If cleaned fewer than 32 teeth, go back to clean the next one.
- If cleaned 32 teeth, stop and rinse the toothbrush.
Here, the condition is whether the number of cleaned teeth is less than 32, and the counter keeps track of how many teeth have been cleaned. After cleaning each tooth, check if the condition is true or false. If it's true (less than 32 teeth cleaned), keep going. If it's false (cleaned 32 teeth), the process can stop. This process is called iteration because the steps are repeated until the condition is met.
Using iteration, the number of steps has reduced from 12 in the first teeth-cleaning algorithm to just six in the algorithm with iteration.
Algorithms contain conditions and counters. This can be applied to a racing game, for example, where players make a turning when it is based on the condition of where they want to go. They can also loop around a roundabout several times, counting each time they make a loop until they meet the desired number of loops.
Amending iteration
Every possible difference in programs cannot be planned for. Sometimes an algorithm needs to be reviewed and updated to meet many different situations.
For example, suppose a person had 10 extra teeth. In the original algorithm, there would have been a further ten steps, giving 42 steps in total. By using iteration, change the condition in step 5 of the new algorithm from 32 to 42. The total number of algorithm steps remains unchanged at 6:
- set number_of_teeth_cleaned to 0
- put toothpaste on toothbrush
- use toothbrush to clean a tooth
- increase number_of_teeth_cleaned by 1
- if number_of_teeth_cleaned < 42 then go back to step 3
- rinse toothbrush