Menu
CoddyTech

Repeat With a for Loop

Part of the Outputs section of Coddy's Arduino journey. Lesson 15 of 24.

To do something an exact number of times, use a for loop. It runs the lines inside its braces again and again, counting as it goes:

for (int i = 0; i < 3; i++) {
  // runs 3 times: i is 0, then 1, then 2
}

The three parts in the brackets, split by semicolons, are:

  • int i = 0: make the counter and start it at 0
  • i < 3: keep going while this is true
  • i++: after each round, add 1 to i, as count++ did

Starting at 0 and stopping before 3 gives three rounds. Writing i <= 3 instead would give four: 0, 1, 2 and 3.

In setup(), a for loop runs its rounds once, when the board starts. Inside the braces, i is an ordinary variable: you can print it or use it in sums.

challenge icon

Challenge

Easy

In setup(), use a for loop to blink the LED on pin 13 three times, then stop:

  • each blink: on for 300 ms, off for 300 ms
  • print the number of each blink, 1, 2 and 3, on its own line
  • leave loop() empty, so the LED stays off afterwards

Press Run, then Check.

Try it yourself

const int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  // blink three times with a for loop, printing 1, 2, 3
}

void loop() {
  // nothing here: the LED stays off after the three blinks
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Outputs

Practice on your own: Arduino playground