How the while loop is working? How to implement it in your program?

The while loop is a structure which will execute a part of the program while the condition is true. The difference with for loop is that in a while loop you don’t need to specify how many times the loop will execute, the condition will just stop the loop.

We will see now how is it working!

while (condition) {
  // Your code
}

Be careful at the infinite loop!

With a while loop, it’s really easy to make an infinite loop which will block our program. For example you can forgetting to increment your variable used in the condition or even a condition which never wiil be false. We advise to be careful that your condition will be false at a moment.

We will see now an example with the while loop:

void setup(){
Serial.begin(9600); // To initialize the serial monitor
int count = 0; // We initialize the variable which will be used to count the loop. 
while (count < 200) { // We execute the loop until the variable count is inferior to 200 
  Serial.println(count); // We display the variable 
  count+=1; // We increment the variable of 1 at each pass
}
}
void loop(){
}

In this program, the while loop will stop at 199 and not 200 because we written a strict inferior but not a strict or equal to.

It’s also possible to write the loop before the condition with do..while.

do..While

The function do while is inverse structure of the while loop : the loop is situated before the condition of the while which is at the end of the loop.

do {
  // Your code
} while (condition); // the condition for the loop

Here is an example of the function do while:

void setup(){
Serial.begin(9600);
int count = 0; // The variable to count the passages in the loop
do {
  delay(50);          // Break of 50 milli-second
  count+=1;  // We increment the variable 
  Serial.println(count); // We display the variable 
} while (count < 100); // We do the loop  while the variable count is lower or equal to 100
}
void loop(){
}

The advantage of the loop which is situated before the condition is that the loop is executed at least one time even if the condition is false. Furthermore, even if there is a strict inferior in the condition it will stop when the value us equal because the loop is before the condition.