A While loop is a part of software that allows a single piece of code to repeat until some condition is met. The condition is put into the argument of the While loop.
While loops are useful because if they did not exist the only option would be to copy code over and over again hundreds or thousands of times. And there would be few ways to change the number of copies that there are easily if the code needs to adjust.
Below is the standard graphical definition of a while loop.
Since the LittleBot Budget is a based on arduino it use a while loop as defined in the C programming language (which is what all arduino boards use). To learn even more about arduino while loops you can visit this page.
The syntax for a while loop is shown below
The "condition" must be a Yes/ No or True/False question. These are called Boolean formulas. If the Condition is TRUE then the loop will run again. If the condition is False then the code in the loop is skipped and the rest of the program runs. A While loop can be described as an IF statments that just repeats until its condition is true.
For example 1<2 in the "condition" would always be TRUE so the loop will run forever, this is called an infinite loop, a loop that never stops. These are bad.
It is better to use a variable that can change in the condition. So that when the variable changes to somthing that is not true then the loop will stop. Generally this is used to have the loop run only a certain number of times.
Let's create an example for the LittleBot using Loops to show this. We will make the LittleBot Turn right then turn left and repeat 5 times. The Full Code is shown below
First create the variables for the While Condition. The Count is the most important. The numberOfTimes is what is considered good coding style rather than simply putting 5 into the while argument
Now you can create the while loop. So if we want the loop to only repeat 5 times. Then we have to create a condition.
The most common type of condition is a count the slowly adds numbers to itself until is makes the condition untrue. In this case each time the loop runs count will add 1. (students can experiment with this by changing that number added to see how it affects the number of times the loop runs). Once the count becomes greater than 5 the loop will stop and the rest of the code in the program will run.
Running the code should result in the robot turning right and then turn left 5 times, then pausing for 10 seconds. Students can change the motions inside of the loop and import actions from thier "One Step at a Time" code.
More advanced students can create more while loops. And maybe even try nesting loops, but that is a more advanced topic. A simple set of experiments is for them to try different conditions and different iteration amounts.
Projects from This