Loops in Arduino

Loops are very important control structure in any programming language. It helps to keep our code small, handy and pretty easy to write and understand. There are loops in Arduino programming language as well. How a loops works is shown below with the help of flowchart. It is the basic logic for loops.

In any loops there are one condition and one conditional code written inside the loop using curly braces ({}). Which will be executed when condition is true. If condition is false at any point, loop will terminate.

Arduino buying links

Amazon link for India Amazon link for other countries

In Arduino there are these loops as listed following.

1.    While loop

In this loops condition is written in parenthesis like this “while(a<5)”. Here ‘a’ is an integer. This loop will execute until ‘a’ is less than 5. If ‘a’ is greater than 5 at any loop iteration, while loops will terminate. Suppose we initialized the ‘a’ with zero at before loop started then we started the loop and we are incrementing ‘a’ inside the loop. Then loop will execute 5 times and at this iteration value of ‘a’ will increment to 5. So, the next time when condition is being checked, it will be false and loop will terminate. Notice here if we will not increment the value of ‘a’ inside the conditional code then while loop will execute infinitely.

If we put ‘1’ instead of “a<5” like “while(1)”, even then while loop will run infinitely. Logic here is same in both condition because the “a<5” returns ‘1’ of ‘0’ depending on condition is true or false. If value of ‘a’ is less than 5 then this statement will return ‘1’ and if ‘a’ is greater than 5 then it will return ‘0’.

Example of while loop

We will see an example of while loop using an Arduino code.

void setup() {                    // code written in this block will run once:
 Serial.begin(9600);             // initializing the serial communication
 int a = 0;                      // assigning 'a' with 0
 while(a<5)                   // while loop stated 
 {
  Serial.println("hello world");        // printing hello world on serial monitor
  a++;                           // incrementing 'a'
 }
}
void loop() {
  // put your main code here, to run repeatedly:
}

We have written all the code in the void setup block to make sure that it runs only once. First we have initialized the serial communication and then we have declared ‘a’ as integer and assigned it with a ‘0’. Then the while loop started. In the condition we have given as we seen previously. Code inside the while loop is written in the curly braces. Inside while loop we have serial printed the “hello world” text. Then we have incremented the ‘a’ by ‘1’ (a++ means increment by ‘1’). Let’s upload the code on Arduino and see the result on serial monitor.

Now let’s see the output when we don’t increment the ‘a’.

void setup() {                     // code written in this block will run once:
 Serial.begin(9600);             // initializing the serial communication
 int a = 0;                      // assigning 'a' with 0
 while(a<5)                   // while loop stated 
 {
  Serial.println("hello world");        // printing hello world on serial monitor
  //a++;                                 // incrementing 'a'
 }
}
void loop() {
  // put your main code here, to run repeatedly:
}

Output:

As you can see it is running infinitely.

We can use the code below as well to run while loop infinitely.

void setup() {                        // code written in this block will run once:
 Serial.begin(9600);             // initializing the serial communication
while(1)                         // while loop stated 
 {
  Serial.println("hello world");        // printing hello world on serial monitor
  }
}
void loop() {
  // put your main code here, to run repeatedly:
}

2.    Do while loop

Do while is same as while loop but difference is that it executes the conditional code first and checks the condition later. Conditional code is written inside “do” block written before while. In this loop code will execute even after condition is not true even once. Let’s see an example.

void setup() {                         // code written in this block will run once:
 Serial.begin(9600);             // initializing the serial communication
 int a = 0;                      // assigning 'a' with 0
 do{                            // conditional code
  Serial.println("hello world");        // printing hello world on serial monitor
  a++;                           // incrementing 'a'
 }
while(a<5);                   // checking condition
}
void loop() {
  // put your main code here, to run repeatedly:
}

Here we put the conditional code in the “do” block and while condition is checking after the conditional code. This time we have terminated the while command using semicolon (;). Now let’s the output of this code at serial monitor.

This is running as the normal while loop. Let’s understand the every iterations of this loop. At first when ‘a’ was zero then do block executed, so “hello world” is printed on serial monitor and ‘a’ incremented to ‘1’. Then condition is checked and it is true at this iteration so loop will execute once again. This process will repeat till ‘a’ is 5. At this iteration “hello world” is printed 5 times and now when condition is checked it will be false and loop will terminate.

Now let’s see the code where condition is not true even once.

void setup() {                    // code written in this block will run once:
 Serial.begin(9600);             // initializing the serial communication
 int a = 0;                      // assigning 'a' with 0
 do{                            // conditional code
  Serial.println("hello world");        // printing hello world on serial monitor
  a++;                           // incrementing 'a'
 }
while(a<0);                   // checking condition
}
void loop() {
  // put your main code here, to run repeatedly:
}

Now let’s see the output of this code on serial monitor.

As you can see that the code is executed once.

3.    For loop

This loop executes the codes a predetermined number of times. In this loop variable is initialized, condition is written and incrimination of variable is done within the for loop parenthesis. Let’s see a for loop initialization.

Example: –         

for(i=0;i<10;i++)

{

    //Conditional code

}

For loop is initialized with keyword “for”. Here ‘i’ is a number which is initialized with 0, checked whether it is smaller than 10 or not and incremented by one within the for loop parenthesis. This ‘i’ should be declared before or we can declare it within the for loop parenthesis like this. Conditional code is written within curly braces.

Example: –          

for(int i=0;i<10;i++)

{

     //Conditional code

}

Now let’s understand what these for loop command will do.

First it will start iteration from number assigned to the variable which is ‘0’ in our case. At first iteration value of ‘i’ will be 0 and this is less than 10, so code inside this loop will execute and ’i’ will increment by one. This process will repeat until value of ‘i’ reaches 10. At 11th iteration value of ‘i’ will be 10 which is not less than 10, so loop will terminate. So, conditional code will be executed 10 times. Now let’s see an Arduino code which consists for loop.

void setup() {                       // put your setup code here, to run once:
  Serial.begin(9600);           // initialized the serial communication
  for (int i=0; i<5; i++)            // for loop initialization
  {
  Serial.println("hello world");        // conitional code
  }
}
void loop() {
  // put your main code here, to run repeatedly:
}

Here we have done same thing we have done in previous all loops. We have given the conditions to iterate the loop 5 times and serial printed “hello world”.

Here ‘i’ is incrementing by one but we can increment as much as we want. We have to just write the statement like this “A+=2”. It will increment the variable with 2. We can choose any number.

If you notice that for loop is not terminated by semicolon (;), what if we close the for loop with semicolon.

int i;
void setup() {      // put your setup code here, to run once:
  Serial.begin(9600); // initialized the serial communication
  for (i=0; i<20; i++);// for loop initialization
  {
  Serial.println("hello world"); 
  Serial.println(i);
  }
}
void loop() {
  // put your main code here, to run repeatedly:
}

In this code we have given the semicolon at the end of for loop. It will not through any error and it will execute. But code within the curly braces is no longer a part of for loop. It is not a conditional code and it will be executed as separate statement. This doesn’t means that for loop isn’t iterating, it is iterating as well as previous but it doesn’t execute the conditional code. The for loop with semicolon creates delay in execution and nothing else.

As you can see here for loop is executed and ‘i’ is incremented to 20 and “hello world” executed separately.

Nested loop

Loops in the loop is called nested loop. We start a loop within a loop. This loop can be of any type. Let’s see examples of all types of nested loops.

Nested while loop

We can start another while loop in an existing while loop. Let’s see how?

int i=0;
int j=0;
void setup() {                  // put your setup code here, to run once:
  Serial.begin(9600);           //initializing serial communication 
while(i<3)                   //outer loop
{
  Serial.print("i is ");                
  Serial.println(i);            // serial printing i
  j=0;                          // assigning j=0
  Serial.println("j is ");
  while(j<3)                 // inner loop
  {
    Serial.println(j);          // serial printing j
    j++;                                // incrementing j
  }
  i++;                          // incrementing i
}
}
void loop() {
  // put your main code here, to run repeatedly:
}

First we have declared two integers “i” and “j” and assigned both with ‘0’.  Then we started the while loop with condition “i<3”, so this loop will iterate 3 times and this loop is called outer loop. Then we serial printed the ‘i’ and assigned ‘j’ with ‘0’. Then we started second while loop with “j<3” condition, this loop is called inner loop. So inner loop will also be executed 3 times. Inside this loop we have serial printed the value of ‘j’ and incremented it by one. Then we closed the inner loop using closing curly bracket. Then we incremented the ‘i’ by one.

When outer loop executes, it prints the value of ‘i’ and assigns the ‘j’ with 0.  Then inner loop runs 3 times and prints the value of ‘j’ which will increment from 0 to 2. So next time, to start iteration from 0 we have assigned ‘j’ with 0 before inner while loop initialization. So, inner loop will run 3 times for every outer loop iteration and outer loop iterates 3 times so inner loop will run 9 times total. Now let’s see the output of this code.

So as you can see that inner loop runs three times for every outer loop iteration. Logic will be same for all types of loops.

Nested for loop

We can do the same thing with for loop.

int i;
int j;
void setup() {          // put your setup code here, to run once:
  Serial.begin(9600);   // initializing the serial communication
  for(i=0;i<3;i++)           // outer loop
  {
      Serial.print("i is ");
      Serial.println(i);        // serial printing i
      Serial.println("j is ");
    for(j=0;j<3;j++) //inner loop
    {
      Serial.println(j);        // serial printing j
    }
  }
}
void loop() {
  // put your main code here, to run repeatedly:
}

In this code we have applied same logic as we discussed earlier. So, output will be same.

Mixed type of nested loop

We can start another type of loop in an existing for, while or any other loop. For example we can start a while loop in the for loop.

int i;
int j;
void setup() {          // put your setup code here, to run once:
  Serial.begin(9600);   // initializing the serial communication
  for(i=0;i<3;i++)           // outer loop
  {
      Serial.print("i is ");
      Serial.println(i);        // serial printing i
      Serial.println("j is ");
      j=0;                              // assigning j=0
     while(j<3)                      // inner loop
    {
    Serial.println(j);          // serial printing j
    j++;                                // incrementing j
  }
  }
}
void loop() {
  // put your main code here, to run repeatedly:
}

Here a while loop is started in for loop. Output will be same here also.

Break and continue statement

Break and continue is very important control structure to control the loops.

Break

It terminates the loop even before some iterations are left. Let’s see an example.

int i;
void setup() {   // put your setup code here, to run once:
 Serial.begin(9600);
  for(i=0;i<10;i++)
  {
    if(i==7)
    {
      break;
    }
    Serial.println(i);
  }
}
void loop() {
  // put your main code here, to run repeatedly:
}

A for loop is initiated and meant to iterate 10 times from 0 to 9. But we have set a condition inside the loop that if ‘i’ is equal to 7 then break the loop. So it will break the loop at 8th iteration when ‘i’ was 7. And it will print the value of ‘i’ from 0 to 6.

Continue

It skips the loop. Let’s see an example.

int i;
void setup() {   // put your setup code here, to run once:
 Serial.begin(9600);
  for(i=0;i<10;i++)
  {
    if(i==7)
    {
      continue;
    }
    Serial.println(i);
  }
}
void loop() {
  // put your main code here, to run repeatedly:
}

As previously a for loop is initiated and meant to iterate 10 times from 0 to 9. But we have set a condition inside the loop that if ‘i’ is equal to 7 then skip (continue) the loop. So it will skip the loop at 8th iteration when ‘i’ was 7. And it will print the value of ‘i’ from 0 to 9 except 7.

3 thoughts on “Loops in Arduino”

  1. You’re so awesome! I do not believe I’ve truly read a single
    thing like that before. So good to find someone with
    some genuine thoughts on this subject matter.
    Seriously.. many thanks for starting this up.
    This web site is something that is needed on the internet, someone with some originality!

Leave a Comment

Your email address will not be published. Required fields are marked *