Repeating with for
Section 9: From blocks to C++ codeLesson 9.4 · ⏱ 7 min
for (int i = 1; i <= 10; i++) = start i at 1, repeat while i ≤ 10, and add one to i each time. Like “repeat” in the blocks, but you also get the number of the turn.
void setup() {
Serial.begin(9600);
for (int i = 1; i <= 10; i++) {
Serial.println(i);
}
}
void loop() {
}
🖥️ The Serial in Robo Maker:
1 2 3 4 5 6 7 8 9 10

🖥️ What happens on the stage?
We ran this code in Robo Maker and the challenge passed: “Bravo! It works”.
📌 Another example: the countdown
for counts from 10 to 1: i-- takes one away each time.
void setup() {
Serial.begin(9600);
for (int i = 10; i >= 1; i--) {
Serial.println(i);
}
Serial.println("Go!");
}
void loop() {
}
10
9
8
7
6
5
4
3
2
1
Go!
✍️ Practise
Write a for that counts to 10.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Count from 1 to 5.
👀 Show the solution🙈 Hide the solution
void setup() {
Serial.begin(9600);
for (int i = 1; i <= 5; i++) {
Serial.println(i);
}
}
void loop() {
}
1
2
3
4
5
Result: 1 2 3 4 5
Medium
The even numbers from 2 to 10 (i += 2).
👀 Show the solution🙈 Hide the solution
void setup() {
Serial.begin(9600);
for (int i = 2; i <= 10; i += 2) {
Serial.println(i);
}
}
void loop() {
}
2
4
6
8
10
Result: 2 4 6 8 10
Hard
The 3 times table: from 3×1 to 3×5.
👀 Show the solution🙈 Hide the solution
void setup() {
Serial.begin(9600);
for (int i = 1; i <= 5; i++) {
Serial.print("3 x ");
Serial.print(i);
Serial.print(" = ");
Serial.println(3 * i);
}
}
void loop() {
}
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
Result: 3 x 1 = 3 … 3 x 5 = 15

