The for loop is good to use when the number of iterations to run for is known. But when the number of iterations is unknown then a while loop tend to be more preferable.
Let's look at the syntax for the while loop.
Condition: this is an expression that is for boolean true. When found true the loop will then execute the code inside the loop.
​
Modifier: a statement that modifies a value used in the condition. The purpose is to at some time make the condition return false and end the loop.
​
As long as the condition is evaluated to true the while loop will continue running. First when the condition is evaluated to false it will stop and the flow will continue executing code following the while loop structure.
​
We can make the while loop iterate for a set number of times if we use a counter as part of the condition.
​
The code for running a while loop 20 times can look like this:
Here the counter variable named i is incremented on each iteration until it reach the value 20. Then the condition will be evaluated to be false and the loop will end.
​
​
Another variation of the while loop is the do-while loop. It is an inverse version of the while loop and makes sure that the code in the loop is being run at least once. First it run the code and then it evaluates the condition after.
The syntax for the do-while loop looks like this: