3A: Loops


Loops (for, while, do…while)

In our Assignment #1, we programmed a set of LEDs to light up in a pattern of our choosing. Some of you chose to create patterns that had a regular pattern or others chose to create a symmetric pattern. There were some who even created their patterns to be shown more than once before going to another pattern.

  1. for
  2. while
  3. do...while

(1) The “for” Loop

The for statement is used to repeat a block of statements enclosed within the curly brackets.

Useful for any repetitive operations or blocks of code. Often used in combination with arrays.

There are three (3) parts to the for loop:

for ( initialization; condition; increment )

For loop
Figure 3.1: Parts of the "for" loop.

Initialization happens first (int i = 0) and exactly once. Each time through the loop, the condition (i < 100) is tested.

If the condition is TRUE, then the statement block is executed.

After the statement block is executed, the increment is executed (i++). The condition is tested again.

When the condition is FALSE, the loop ends.

(2) The “while” Loop

While loops will loop continuously and infinitely until the condition within the parentheses becomes FALSE.

Useful when something within your code changes and needs to be tested. This could be an increment variable (similar to in the for loop), or in response to an external condition (e.g. such as from a sensor).

while ( condition ) {
    // statements
}

Example:


[ Show an example code using the "while" statement ]

(3) The “do…while” Loop

The do…while loop works in the same manner as the while loop. However, the condition is tested at the end of the loop, instead of the beginning.

The do…while loop will ALWAYS run at least once.

do {
   // statement block
} while ( condition );

Example:


[ Show an example code using the "do...while" statement ]