Curriculum
Course: c++ Basics and Importants
Login
Text lesson

For Loop Explanations

Why do we need a loop?

Suppose I want the servo motor to move from 0° to 180°.

I could write:

 
myServo.write(0);
myServo.write(1);
myServo.write(2);
...
myServo.write(180);
 

But that would mean writing more than 180 lines of code!

Instead, we use a for loop, which allows us to repeat the same instructions automatically.


Look at this code:

 
for (int angle = 0; angle <= 180; angle++) {
myServo.write(angle);
delay(15);
}
 

A for loop has three parts:

 
for (initialization; condition; increment)
 

Let’s understand each part.


Part 1: Initialization

 
int angle = 0
 

Here, I create a variable called angle and give it a starting value of 0.

So, the servo starts from 0 degrees.


Part 2: Condition

 
angle <= 180
 

This means:

Continue repeating as long as the angle is less than or equal to 180.


Part 3: Increment

 
angle++
 

This means:

Increase the value of angle by 1 after every repetition.

It is the same as:

 
angle = angle + 1;
 

First time through the loop

 
angle = 0
 

So,

 
myServo.write(0);
 

The servo moves to 0°.


Second time

 
angle = 1
 

So,

 
myServo.write(1);
 

The servo moves to 1°.


Third time

 
angle = 2
 

So,

 
myServo.write(2);
 

The servo moves to 2°.


This continues:





...
180°
 

When the angle becomes 181,

 
181 <= 180
 

is false.

So the loop stops.


Now look at the second loop:

 
for (int angle = 180; angle >= 0; angle--) {
myServo.write(angle);
delay(15);
}
 

Here,

  • We start from 180.
  • Continue as long as the angle is greater than or equal to 0.
  • Decrease the angle by 1 every time.
 
angle--
 

means

 
angle = angle - 1;
 

So the servo moves like this:

180°
179°
178°
...


 

Remember this:

 
for (int angle = 0; angle <= 180; angle++)
 

means:

Start from 0, continue until 180, and increase by 1 each time.

And

 
for (int angle = 180; angle >= 0; angle--)
 

means:

Start from 180, continue until 0, and decrease by 1 each time.


One-line definition:

A for loop is used when we know how many times we want to repeat a set of instructions.

×
×

Cart