Tags: ,

The for instruction allows code blocks to be repeated. It is the first step towards more efficient and readable code.

Syntax of the instruction for

The for instruction takes, as input, a counter whose increment and end condition is defined. It is often used in conjunction with array lists to perform operations on the data they contain?

  for(initialization;condition;increment){
    <listof instructions>;
  }

On initialization, an integer is set to contain the counter. The stop condition will be the result of a logic test (usually a limit value. And the increment will be an operation that defines how the counter evolves with each revolution.

In the following example, the code will count up to 10 with each value displayed on the serial monitor:

  • initialization: we initialize an integer i to 0
  • condition: the loop will stop when i reaches the value 10
  • increment: the counter i changes by 1 with each execution
void setup() {
  Serial.begin(9600);
}

void loop() {
  for(int i=0;i<=10;i=i+1){
    Serial.println(i);
  }
  delay(500); //delay for monitor display
}

In the following example, the algorithm counts from 10 to 0.

for(int i=10;i>=0;i=i-1){
 Serial.println(i);
}

For the definition of the increment of the variable, it is possible to set any function. Example:

  • i=2*i to count even numbers
  • i=2*i+1 to count odd numbers
  • i=pow(i,2) a square function
  • i++ equals i=i+1
  • i– equals i=i-1

Initialization can be defined outside the for loop. In this case, pay attention to the name and initialization of your variables. In the following example, the code will first count from 0 to 10 and then count from 3 to 10 the following times.

int index=0;
void setup() {
  Serial.begin(9600);
}

void loop() {
  for(index;index<=10;index=index+1){
    Serial.println(index);
  }
  index=3;
  delay(500); //delay for monitor display
}

Other syntaxes

It is possible to forget the braces if the for loop contains only one instruction.

for(int i=0;i<=10;i=i+1) Serial.println(i);

It is sometimes interesting to run several loops in parallel. These are called nested loops. In the following example, for each execution of the first loop, the second will count up to 5.

for(int i=0;i<=10;i=i+1){
   for(int j=0;j<=5;j=j+1){
       Serial.print(i);
       Serial.print(F("-"));
       Serial.print(j);
   }
}

Things to remember

  • the for instruction takes as input the initialization of a counter, a stop condition and an increment definition.
  • the for loops can be nested
  • the instruction block is located between braces {}.
  • If there is only one instruction, then there is no need for a brace.

Make sure you understand the arrays, logical and increment operators in order to use the for instruction correctly. Once you have mastered this instruction, you will be able to create algorithms more efficiently.

Sources