Understanding the tutorial code

Hey, so I just bought an Arduino just yesterday and wanted to get into things and I’m following through the tutorial but felt like something wasn’t explained? - Sorry if this sounds like a dumb question!

{
#define delayTime 50 // fading time between colors

redValue = 255; // choose a value between 1 and 255 to change the color.
greenValue = 0;
blueValue = 0;

// this is unnecessary as we've either turned on RED in SETUP
// or in the previous loop ... regardless, this turns RED off
// analogWrite(RED, 0);
// delay(1000);

for(int i = 0; i < 255; i += 1) // fades out red bring green full when i=255
{
redValue -= 1;
greenValue += 1;
// The following was reversed, counting in the wrong directions
// analogWrite(RED, 255 - redValue);
// analogWrite(GREEN, 255 - greenValue);
analogWrite(RED, redValue);
analogWrite(GREEN, greenValue);
delay(delayTime);
}

The part I don’t understand is the for(int i) line.

Read this:
https://www.arduino.cc/reference/en/language/structure/control-structure/for/

It’s also important to understand the sequencing of the expressions in a for loop. First, let’s number the expressions:

(1) (2) (3)

  • for (int i = 0; i < 255; i += 1) { // Start of loop body*
  • // statements controlled by the for loop*
  • } // End of for loop body and statement block*

Note the three expressions are separated by semicolons.
The first expression executed is expression (1). It is only executed once, so it is usually used to set any preconditions needed for the loop to execute as desired. In this case, it defines variable i and initializes it to zero.

(2) The second expression often is a conditional test to see if we should execute the statements contained between the opening and closing braces of the for loop (i.e., the for loop body). If the result of the expression is logic True, the statements are executed. If the expression is logic False, they are skipped. Note that it is possible for expression (2) to be False the first time and none of the statements are ever executed. If you write statement (2) in such a way that it is never falsified, you get a loop that never ends (i.e., and infinite loop) and your program “locks up”.

(3) Expression (3) is often an operation on the variable that controls the loop; variable i in this example. It is executed after all of the statements between the braces have been processed. Visually, you can pretend that expression (3) sits at the bottom of the loop, just before the closing brace. In this example, variable i is increase by 1 by expression (3). More often than not, this would be written as i++.

Immediately after expression (3) is processed, program control goes back to expression (2) to see if we need to make another pass through the loop. If so, the for loop statement block is executed again. If not, program control is sent to the first statement that follows the closing brace of the for loop.