Lesson: 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.

This loop will increment x to 3 then continue looping until autoMode (a boolean variable) becomes false, 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 ensuring the loop is executed at least once before the comparison is checked.

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.


Lesson navigation: