for
Description
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.
Syntax
If there is only one statement, the curly braces can be omitted.
Parameter Values
- initialization: happens first and exactly once.
Example Code
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:
Example explained:
- 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:
Loop Forever
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.
Others
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:
Generates: 2,3,4,6,9,13,19,28,42,63,94
Another example, fade an LED up and down with one for loop:
See Also
- Language : break
- Language : continue
- Language : do...while
- Language : else
- Language : goto
- Language : if
- Language : return
- Language : switch...case
- Language : while
※ ARDUINO BUY RECOMMENDATION
Arduino UNO R3 | |
Arduino Starter Kit |