Site icon AranaCorp

Summary on the instruction for in C

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:

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:

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

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

Exit mobile version