while Loop
This lesson essentially explains what a while loop is and how to use it in the code.
We'll cover the following
while loop #
The while
loop is similar to the if
statement and essentially works as a repeated if
statement. Just like if
, while
also takes a logical expression and evaluates the block when the logical expression is true. The difference is that the while
statement evaluates the logical expression and executes the statements in the block repeatedly, as long as the logical expression is true, not just once. Repeating a block of code this way is called looping.
Here is the syntax of the while statement:
while (a_logical_expression) {
// ... expression(s) to execute while true
}
For example, the code that displays ‘Take cookie’ and ‘Eat cookie’ as long as there is cookie looks like this:
Get hands-on with 1400+ tech skills courses.