Adventures in Science: Arduino Loops

Time for the ever-popular loops discussion! We look at the three basic loops you can use in Arduino.

Favorited Favorite 1

This week, we examine loops in Arduino. Specifically, we look at while, do while, and for loops.

The while loop is intended to run code inside the curly braces { } as long as the condition specified behind the while statement is true. For example, the following code would print "Hi" three times before exiting the loop:

int i = 0;
while ( i < 3 ) {
    Serial.println("Hi");
    i++;
}

Note that the condition (the part in between the parentheses ( )) can include any of the relational operators we discussed in the conditional statements video or the compound conditional statements we talked about in the logic operators episode.

The do while loop is similar, but it guarantees at least one execution of the code between the curly braces, as the condition check occurs after the code. For example, the following code prints "Hi" once, even though i fails the condition check the first time through.

int i = 0;
do {
    Serial.println("Hi");
    i++;
} while ( i < 0 );

Finally, the for loop is intended to run a piece of code a specified number of times (although you can make it do other things). We can make the while loop example above cleaner by condensing it into a for loop:

int i;
for ( i = 0; i < 3; i++ ) {
    Serial.println("Hi");
}

Note that in C++ and modern implementations of C, you can declare the i variable inside the for loop's initialization: for ( int i = 0; i < 3; i++ ) {...}, but I left it out of the video, as I plan to cover that in a future episode dealing with scope.

Any tips or tricks you'd like to share when it comes to loop? Let us know in the comments!


Comments 3 comments

  • Member #394180 / about 8 years ago / 2

    A few things. You can code a nice clean forever loop as either

    for (;;)
    {
    }
    

    or

    while (true)
    {
    }
    

    You get out of the loops using the break, assuming you want to get out at all.

    Next, in the for-loop "afterthought" (cute name, BTW), using post increment/decrement is traditional, but when using C++ variables for loop control, variables that can be complex objects with complex increment operators, such as iterators, it's actually more efficient to use pre increment/decrement. That is:

    for (map<string, int>::const_iterator i=foo.begin(); i!=foo.end(); ++i)
    {
    }
    

    Another way to exit loops is by throwing an exception.

    for (;;)
    {
        throw runtime_error("Oopsie"); 
    }
    

    The exception unwinds the stack, causes a clean scope exit and cleans up all automatic variables (including calling the destructors for any that may be objects).

    It's sort of funny to consider that break and continue are structured programming mutants of the good old goto and that throw is the computed goto on steroids.

    One thing you should never do is a goto into a loop:

    int i;
    
    for (i=0; i<10; i++)
    {
    dont:
    }
    
    i = 5;
    goto dont;
    

    Believe it or not I actually saw this construct being used to re-execute the loop 5 more times after the first 10 times. The brainless bozo was using it to implement a retry strategy. Ugh! That's the C/C++ equivalent of covfefe :-)

  • sgrace / about 8 years ago / 1

    A trick is that you can have embedded for-loops where only one loop has initialization and conditional happens in both:

    int i, j;
    for ( i = 0, j = 0; i < 16; ++i, j += 4) { ...
        for( ; i < 64; ++i) { ...} }
    

    If you haven't guessed, this is from a version of SHA256.

    I don't recommend doing this, but there are some advantages if a loop variable will be used in both loops and they will modify some data (in this case for SHA256, it is used in padding).

    • MikeGrusin / about 8 years ago * / 1

      If you haven’t guessed, this is from a version of SHA256.

      Classic SGrace! ;)

Related Posts

Recent Posts

Tags


All Tags