for loops

Home

Introduction

for Loop

 The syntax of for loop is:

for (initializationStatement; testExpression; updateStatement) {
  // statements that you want to iterate
// maybe blinking an LED?
// maybe some dance moves? }

How for loop works?

1. The initialization statement is executed only once.

2. The test expression (a conditional) is evaluated.  If the test expression is false (zero), the for loop is terminated.  

3. If the test expression is true (nonzero), code inside the body of the for loop is executed, then the update statement is executed.

4. This process (steps 2 and 3) repeats until the test expression is false.

The for loop is commonly used when the number of iterations is known.


for loop Flowchart

Flowchart of for loop in C programming language

The above tutorial was adapted by Mr. Stewart from this website.

For Loops Vs While Loops

Both for and while loops serve similar purposes.  Why use one or the other?

For Loops:

  1. Execute a known number of iterations.

  2. Uses a single line of code to control the loop

  3. Reminds the coder to increment the loop variable

While Loops

  1. Easier to read for those unfamiliar with for loop syntax

  2. Works well to wait for something to happen (e.g. a button to be pressed)

  3. Prone to infinite loops more than for loops if you either

  4. a.) forget to increment the loop variable

    b.) or have incorrect syntax (a ; after the while statement or missing {} symbols)

Often these loops can be used interchangeably:


Built-In Example

1. Just like the Blink example, there is a sample for loop available for your reference in the Arduino IDE under File->Examples->05. Control->ForLoopIteration

2. Open this Example now and read it.

3. Refer back to this Example whenever you need a refresher on for loop syntax.

Check Your Understanding

1.  The for loop has three different parameters (use the names given above):

   A. The first is the , which runs once at the start of the loop. 

   B. The second is the , which is evaluated to see if it is (four letters) before each time the loop executes

   C. The third is the , which executes after the of the for loop runs.

2. The built-in for loop example blinks the LEDs up and down the side of the board (for reference, the USB goes into the top of the board).


Next Page