for

The for clause is used to repeat a block of statements enclosed in braces. The increment counter is typically used to increment and end the loop. The for statement is suitable for any repetitive actions and is often used in conjunction with arrays of data / output collections.

The header of the for loop consists of three parts:

for (initialization; condition; increment) {statements running in a loop}

Initialization is performed the very first and once. Each time in the loop, the condition (condition) is checked, if it is true, the block of operators is executed and the increment (increment) is executed, then the condition is checked again. When the logical value of the condition becomes false, the loop ends.

Example

// LED dimming using PWM output
int PWMpin = 10; // LED in series with a 470 ohm resistor on 10 pins
void setup() {
 // no setup needed 
}
 
void loop() {
   for (int i=0; i <= 255; i++){
      analogWrite(PWMpin, i);
      delay(10);
   }
}

Application tips

The for loop in C is much more flexible than the for loop in other programming languages, for example, in BASIC. Any of the three or all three header elements may be omitted, although semicolons are required. Also, operators for initialization, conditions and cycle increments can be any valid in C operators with independent variables, and use any type of C data, including data with floating point (floats). These unusual for the for loop types of operators allow for the software solution of some non-standard problems.

For example, using multiplication in the loop counter operator allows you to create a logarithmic progression:

for(int x = 2; x < 100; x = x * 1.5){
    println(x);
}

Generated: 2, 3, 4, 6, 9, 13, 19, 28, 42, 63, 94

Another example is a gradual decrease or increase in the signal level to the LED using one for loop:

void loop(){
  int x = 1;
  for (int i = 0; i > -1; i = i + x){
      analogWrite(PWMpin, i);
      if (i == 255) x = -1; // switching control at maximum
      delay(10);
   }
}