While Loops are similar to for loops because they repeat segments of code. However in a for loop, you specify how many times a segment of code should repeat. With a while loop, you need to set the condition to make the code stop repeating the specified segment.
Setting the condition is similar to that of an if statement that checks to see if a condition is True or False.
Look at the example below. The code repeats until the condition of the
count > 0. Once this is no longer True, the code will stop repeating.
If a while loop does not contain an input or an incrementing or decrementing variable, you may be stuck in an infinite while loop! See the example below.
Try to code a programme in the console below that will:
- Ask the user a question
- repeat the question infinitely until;
- the user gets the answer correct for example
what is 2+2?
ask the user for an answer until they get it correct