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

1for (initialization; condition; increment) {
2 // statement(s);
3 }

Parameters

  • initialization
    : happens first and exactly once.
  • condition
    : each time through the loop,
    condition
    is tested; if it’s
    true
    , the statement block, and the increment is executed, then the condition is tested again. When the condition becomes
    false
    , the loop ends.
  • increment
    : executed each time through the loop when
    condition
    is
    true
    .

Example Code

1// Brighten an LED using a PWM pin
2 int PWMpin = 10; // LED in series with 470 ohm resistor from pin 10 to ground
3
4 void setup() {
5 // no setup needed
6 }
7
8 void loop() {
9 for (int i = 0; i <= 255; i++) {
10 analogWrite(PWMpin, i);
11 delay(10);
12 }
13 }

Notes and Warnings

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:

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

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

Another example, fade an LED up and down with one

for
loop:

1void loop() {
2 int x = 1;
3 for (int i = 0; i > -1; i = i + x) {
4 analogWrite(PWMpin, i);
5 if (i == 255) {
6 x = -1; // switch direction at peak
7 }
8 delay(10);
9 }
10 }

See also

Suggest changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.