Lesson: Gonzalez WHILE Statement

Explore program flow control using the WHILE statement.

Understand how to employ comparisons to alter program flow with the WHILE statement.


Another form of flow control allows us to have a statement (or block of statements) repeatedly executed while a comparison is true. This is done with the while statement. The form of the while statement is:

Here are some examples, each using a comparison on a variable z as the boolean value. Assume z = 0 at the start of this code:

If the comparison is false when the while condition is checked the first time, the block of statements is not executed. Typically the looping of the while statement is controlled by the comparison but it is possible to exit the loop's block of statements with the break statement. The break statement ends the while and continues execution after the end of the while block. Here is an example, assume x = 0:

This while will loop 3 times, making x reach a value of 3. The if statement is checked on each loop. When the comparison of x and 3 gives true, the code will execute a ‘break’. This means that the code leaves the current loop, and will continue after the last }. The while condition is not checked again.
You can also modify loop execution with the continue statement. Continue causes the rest of the statements in a while block to be skipped and the while loop comparison to be checked again to see if the while block should be repeated.

assuming autoMode is true to start, this loop will increment x to 3 then continue looping until autoMode (a boolean variable) becomes false, without further incrementing x. Remember the condition is tested first, so if autoMode was false when we first hit the while, the while block would be skipped.

So far we looped on the condition being true. You can loop while the condition is false by changing the condition or inverting the true condition by preceding it with the ! (not) operator:

Assuming autoMode is false to start, this loop will increment x to 3 then continue looping until autoMode (a boolean variable) becomes true, without further incrementing x.

Watch a video about looping (stop after the while discussion). Here is a detailed discussion of the while statement. Here is more about break and continue statements. Here are the above examples in CodingGround.

Note that while and do-while are essentially the same. With the do-while, the comparison is done at the end of the loop, thus insuring the loop is executed at least once before the comparison is checked.

This do-while block is executed at least once with continued looping dependent on the result of the comparison.

In robotics, the while statement is often used to loop and monitor the input from joysticks or controllers and operate the robot in response to those inputs. For instance, a while loop could continue until the variable that indicates a match is in progress goes false.