The while
loop is the simplest and most frequently used loop. It consists of a loop condition that determines the number of times the while
loop executes a block of statements. The loop condition is usually an expression that evaluates to true or false. However, if you recall our previous discussion of true-like and false-like values, the expression could technically be of any data type. Non-zero numbers such 3 or 5 are evaluated as true while 0 is evaluated as false. Other data types also have similar cases whereas the value itself can be expressed as a true or false value.
The while loop above prints the numbers from 1 to 10 in order to the console. Let's take a look at how this works. The loop condition is the expression inside the brackets, in this case, counter < 11
. As long as the expression is true, the statements inside the while
loop will be repeatedly executed. The value of counter
starts as 1, and continues to increase by one after the while
loop is executed.
After the first run of the while
loop, the value of counter
is 2 and the while
loop will keep running until counter
is 11. This is because "11 < 11" is false, which is why the while
loop will stop running. If the statement counter+=1
does not exist, the value of counter
will always be 1, causing the while
loop to run infinitely, causing an infinite loop.
Edit Me on GitHub!