# While Loop

In programming, a while loop is a way to repeatedly run lines of code as long as a condition is met.

int i = 3;
while(i > 0)    //as long as i is greater than 0, keep repeating
    i--; //decrement i

In the above example, the condition for the while loop is if the variable i is greater than 0. i starts at 3 and then at every loop iteration i is decrementing. When i reaches 0, the condition will not be satisfied and it will return false. This is when the loop will terminate.

Inside the scope of the while loop, we can write anything we want. For example, let's say we want to go through all the numbers from 0 to 10 and print only the numbers that are even.


Modify the code to go through the integers from 10 to 20 and print the odd numbers only.

int var = 10;
void setup() 
  while(var <= 20)
      if((var % 2) != 0)
      var++;    //this is very important to change the value of var

  Serial.println("Went out of the while loop");
void loop() 


# Endless Loop

What happens if the logic statement for our while loop always returns true? The loop will never break!

The while loop will keep on iterating and the line "Went out of the while loop" will never be printed.

# break and continue

In C++ there are two keywords that we can use to jump out of a loop or skip an iteration.

# break

break can be used to break the loop. In the above example, the loop will never break because our condition is always true.

However, we can make force a break inside the loop by calling break;

The following example checks at every iteration if var is equal to 5 then breaks the loop. The condition for the while loop is still true, the loop breaking is enabled manually by us.

# continue

Sometimes we just want to skip a loop iteration without breaking the full loop. We can do that by calling continue; whenever we want to skip a loop iteration. The loop will then jump to the next iteration.

The following example checks if var is an odd number, it skips the iteration and does not reach line 12 to print the value of var.

# Exercise


Write a program that combines the behaviour of both programs that we saw:

  • if var is equal to 5, the loop breaks
  • if var is odd, the iteration is skipped and the value of var is not printed