While Loop (indefinite loop)
A while loop is used when we need to execute a set of instructions more than once, but we don’t know how many times we will have to do it.
Common examples of this situation are where we are trying to get a good user input (i.e. within a certain range) or to tell if the user wants to repeat some actions again (i.e. playing a game or choosing another item to order).
Just as with If statements, a loop has one or more conditions that must be met (evaluate to true) before the loop will begin. The same conditional statements that are used with If statements can be used with loops
For instance:
- While total > 0
- While isPlaying = true
- While pay < 100 and hours > 10
A loop must have 3 components in order to run:
A loop variable That is updated during the course of the loop If it is not updated we have an endless loop (infinite loop = bad)
An exit condition What condition does our loop variable need to meet to get us out of the loop
A loop body The statements that are executed while the loop is running Flowgorithm offers 3 types of loops
While – we are not sure how many times our loop needs to run (indefinite loop)
- For – we know from the start exactly how many times our loop needs to run
Do – this loop executes once and then looks to see if the condition is met (We will not be using Do loops in this subject) To add a loop to a Flowgorithm program
Ensure that you have already declared the loop variable and set it to some value
- Make sure you declare any variables that will be needed before you start the loop
- Click on the vertical line on the flowchart and choose the type of loop (the next example uses a while loop)
- Enter the conditional expression and click OK
- Click on the loop line and enter all the actions taken in the loop
- Ensure that the loop variable is updated when the exit condition is reached (i.e. user wants to quit)