The while loop
The while function will run until the condition that is tested becomes false, thus the loop can run one time or multiple times. It is well suited when we don’t know how many times we should loop.
So let’s create a simple loop where we increment the numbers of steps by 2 until we reach 10 steps and when we reach it, we output a congratulation message.
So we have declared 3 different variables:
- steps – which represent the number of steps we accomplish, we increment it by 2 for each loop
- total – it will add up all the steps that have been made
- target – represents the number of steps we must take, in order to succeed
So we will loop until the total number of steps will be the same as our target (in our case it is 5 times). Then, once we have reached our target, the output message is shown.
The while function has a particular case, the repeat-while loop.
The repeat-while loop
The repeat-while loop will repeat a statement while a condition is met. The difference between the two loops is that, repeat-while first runs the statement and then checks the condition. The while loop, will first check the condition and will run the statement only if the condition is true.
So if we take the example from above, and set the initial value for steps at 10, then the total number of steps that will be accomplished is 12 when we use the repeat-while loop and only 10 with the while loop.