The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is usually used to increment and terminate the loop. The for statement is useful for any repetitive operation, and is often used in combination with arrays to operate on collections of data/pins.
If there is only one statement, the curly braces can be omitted.
- initialization: happens first and exactly once.
- increment: executed each time through the loop when condition is true.
Example Code 1
In the example above, the code in the loop will run, over and over again five times.
The result on Serial Monitor:
- Initialization: int i = 1 sets a variable before the loop starts.
- Condition: i <= 5 defines the condition for the loop to run. If the condition is true (i is less than or equal to 5), the loop will start over again. if it is false (i is greater than 5), the loop will end.
- Increment: i++ increases a value each time the code block in the loop has been executed.
The above code is equivalent to:
Example Code 2
※ NOTES AND WARNINGS:
The following while loop loops forever:
How to escape the for loop
There are three ways to escape the for loop:
- The condition of the for loop becomes false.
- The execution of the code reaches a break statement inside the loop.
- The execution of the code reaches a goto statement inside the loop, which jumps to a label located outside of the loop.
The C++ for loop is much more flexible than for loops found in some other computer languages, including BASIC. Any or all of the three header elements may be omitted, although the semicolons are required. Also the statements for initialization, condition, and increment can be any valid C++ statements with unrelated variables, and use any C++ datatypes including floats. These types of unusual for statements may provide solutions to some rare programming problems.
For example, using a multiplication in the increment line will generate a logarithmic progression:
Another example, fade an LED up and down with one for loop: