Sometimes we need to be able to program our Propeller to repeat certain operations. This is useful for simple things, such as blinking a light, and more complex tasks, such as robotic sensor navigation.
Blocks of repeating code are called loops. The C while loop can be set up to repeat a code block while some condition is true. A while loop can also be set up to repeat endlessly, but there is a trick for escaping endless loops as well. Let's try all of these.
/* Repeat While.c Keep displaying n = n + 5 every fifth of a second while n < 100. */ #include "simpletools.h" // Include simpletools int main() // main function { int n = 0; // Declare n, initialize to zero while(n < 100) // Repeat while n less than 100 { print("n = %d\n", n); // Display name & value of n n = n + 5; // Add 5 to n each time through pause(200); // 0.2 s between repetitions } print("All done!"); // Display all done }
Inside main, a variable n is declared and initialized to zero. Then, while (n < 100) starts a loop that will keep repeating the code block below it as long as (n < 100) is true.
Each time through the loop, n = n +5 increases the value of n and then a print displays the new value in the SimpleIDE terminal.
Eventually, n = 100 so (n < 100) is no longer true. At that point, the code execution skips to the first instruction below the while loop's code block. In this case, it's print("All done!");.
Keep in mind that conditions like a < b and n < 100 evaluate to 1 if they are true or 0 if they are false. Like if statements, while statements execute their code block when the condition is 1, or really any value other than zero.
Think about the Did You Know section for a minute. Can you guess how to make a while loop repeat forever? If you change while(n < 100) to while(1), you’ll have an endless loop.
Even an endless loop doesn’t have to be endless thanks to the C language’s break keyword.
What do you think would happen if you move the break statement to just underneath n = n + 5 inside the while loop's code block? Try it!