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; and

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\n  1\n  2\n

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\n  6\n  7\n.

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\n  13\n  14\n.

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\n  5\n  6\n  7\n  1\n  5\n  6\n  7\n  2\n  5\n  6\n  7\n.

.

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.

Categories: ArduinoTutorials

0 Comments

Leave a Reply