انتقل للمحتوى
Robo EgyptRobo Egypt
☰ Course contents
Robo Maker: home
0. Lab tour1
1. The start: the Arduino6
2. Wiring and the traffic light4
3. Inputs: the button4
4. Sound and movement5
5. Sensors and numbers5
6. Distance, the screen and colours5
7. Motors and the car4
8. The project: the city's smart gate3
9. From blocks to C++ code5
10. Sensors and screens in code5
11. Smart systems5
12. Bluetooth: control from the phone1

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.

⚙️ Count from 1 to 10
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
The numbers in the Serial
The numbers in the Serial
🖥️ 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.

⚙️ The countdown
void setup() {
  Serial.begin(9600);
  for (int i = 10; i >= 1; i--) {
    Serial.println(i);
  }
  Serial.println("Go!");
}

void loop() {
}
🖥️ Serial Monitor
10
9
8
7
6
5
4
3
2
1
Go!
✍️ Practise
Write a for that counts to 10.
✍️ Practise here in the lessonor open the lab in a new page ↗

🎯 Challenge yourself

Easy

Count from 1 to 5.

👀 Show the solution
⚙️ Solution
void setup() {
  Serial.begin(9600);
  for (int i = 1; i <= 5; i++) {
    Serial.println(i);
  }
}

void loop() {
}
🖥️ Serial Monitor
1
2
3
4
5

Result: 1 2 3 4 5

Medium

The even numbers from 2 to 10 (i += 2).

👀 Show the solution
⚙️ Solution
void setup() {
  Serial.begin(9600);
  for (int i = 2; i <= 10; i += 2) {
    Serial.println(i);
  }
}

void loop() {
}
🖥️ Serial Monitor
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
⚙️ 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() {
}
🖥️ Serial Monitor
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

Finished the lesson? Mark it so your progress counts.