Repetition: for loops

Theory

A for loop is used to count over a sequence of numbers. It is best explained by example.

Example 1

This code will say “Hello” ten times.

void loop() {
  int i;

  for (i = 0; i < 10; i++) {
    Serial.println("Hello");
  }

The statement i++ is exactly equivalent to i = i + 1. It simply adds one to the value of i. This code runs ten times because the condition is i < 10.

Example 2

This code will print the numbers 15, 14, 13, 12, 11 and 10, and also compute the total of all of these numbers.

void loop() {
  int i;
  int total = 0;

  for (i = 15; i >= 10; i--) {
    Serial.println(i);
    total = total + i;
  }
  Serial.print("Total is: ")
  Serial.println(total);

The statement i-- is exactly equivalent to i = i - 1. It subtracts one from the value of i.

The general pattern

The for loop has three parts inside its parentheses and separated by semicolons. These are, in order:

  1. The “initialiser” gives the starting value of the loop variable (which above is i).
  2. The “condition” describes the test that must be satisfied for the loop body to be run. If the condition is false, the loop ends.
  3. The “update statement” indicates how to change the loop variable between each iteration of the loop. For example, typically it will add or subtract a certain value.

Exercise

Write code that will take the average of 10 measurements of the light sensor and print it to the serial port.


This work is licensed under a Creative Commons Attribution 4.0 International License. For comments or corrections, please contact [email protected].