Loops:

Loop statements are statements which can be executed again and again until a given condition is true. There are many types of loops. They are:

  • For loop
  • While loop
  • do while loop

For loop:

There are three statements which we have to initialize for a for loop. They are:

  • Initialization: which is executed once at the start of the loop.
  • Condition: which is checked everytime before the code inside the loop is executed.
  • Incrementation / decrementation : which is done everytime before the code inside the loop is executed.

Example:

int i = 0;
for (i = 0; i<3; i++){
Serial.println(i);
}

Here, we initialized a variable i = 0, then we are incrementing i by 1, and we are printing i, till the value of i is less than 3 (i = 2). hence the output of the code will be

0
1
2

While loop:

A while loop is executed till the condition written inside the parenthesis is false.

Example:

int I = 5;
while(I<8){
Serial.println(I);
I++;
}

Here, we initialized a variable I = 5, then we are incrementing i by 1, and we are printing i, till the value of I is less than 8 (i = 7). hence the output of the code will be

5
6
7

Do While loop:

A do while loop is executed till the condition written inside the parenthesis is false.This loop will be executed at least once even if the given condition is false.

Example:

Int I = 12;
do{
Serial.println(I);
I++;
}while(I<15);

Here, we initialized a variable I = 12, then we are incrementing i by 1, and we are printing i, till the value of I is less than 15 (i = 14). hence the output of the code will be

12
13
14

There are two special types of loops which are explained below:

Nested loop:

Anything which is present inside something is called as nested. Similarly, any loop which is present inside a loop is known as nested loop.

Example:

int j = 0;
for (j = 0; j<3; j++){
Serial.println(j);
Int I = 5;
while(I<8){
Serial.println(I);
I++;
}
}

Here, we initialized a variable j = 0, then we are incrementing j by 1, and we are printing j, till the value of j is less than 3 (j = 2). Inside every incrementation, we initialized a variable I = 5, then we are incrementing I by 1, and we are printing I, till the value of I is less than 8 (I = 7). hence the output of the code will be

0
5
6 
7
1
5
6
7
2 
5
6 
7

Infinite loop:

An infinite loop will run infinite number of times(because of lack of terminating condition.

Example:

Int I = 1;
while(I<3){
Serial.println(I);
}

Here, the value of I isn’t changing, so the loop will run infinite number of times.

1
1
1
1
1
1
1
.
.
.
.

Next Post:Uploading code to and introduction to com port to Arduino board

Previous Post:If conditions in Arduino IDE

Categories: ArduinoTutorials

1 Comment

Arduino Tutorials:If conditions in Arduino IDE - projectsflix · January 3, 2021 at 5:45 pm

[…] Next Post:Loops in Arduino IDE […]

Leave a Reply