3B: Loops (“break” and “continue”)


There are many instances when we want to use a loop. But what can we do when we want to break out of a loop? There are two types of code that we use in cases where we want to intentionally stop execution of our code that is in a loop.

  1. “break”
  2. “continue”

The “break” Statement

The “break” statement is used to stop execution and jump out of the loop completely. It is used to exit out of a “for”, “while” or “do…while” loop bypassing the normal loop condition.

The “break” statement can also be used to exit from a “switch” statement.

 

Example:

for (x = 0; x < 255; x ++)
{
   digitalWrite(pin, x);
   sensorVal = analogRead(sensorPin);
    if (sensorVal > threshold){  // bail out on sensor detect
      x = 0;
      break;
    }
    delay(50);
}

 

The “continue” Statement

The “continue” statement is similar to the break statement, but it does not stop execution of the loop and jump out of the loop. The “continue” statement skips the current iteration of the loop (“for”, “while”, “do…while”).

The loop will continue to the increment value and conditional expression is evaluated.

 

Example:

for (x = 0; x < 255; x ++)
{
if (x > 40 && x < 120){ // skip to the end of the loop
continue;
}

digitalWrite(pin, x);
delay(50);
}