while

Description

A while loop will loop continuously, and infinitely, until the condition inside the parenthesis, () becomes false. Something must change the tested variable, or the while loop will never exit. This could be in your code, such as an incremented variable, or an external condition, such as testing a sensor.

Syntax

while (condition) { // statement(s); }

If there is only one statement, the curly braces can be omitted.

while (condition) // a single statement;

Parameter Values

  • condition: a boolean expression that evaluates to true or false.

Example Code

void setup() { Serial.begin(9600); Serial.println("====== TEST START ======"); int i = 0; while (i < 5) { Serial.print("Inside the WHILE loop: i = "); Serial.println(i); i++; // increase i by 1 } Serial.println("====== TEST END ========"); } void loop() { }

In the example above, the code in the loop will run, over and over again, as long as a variable (i) is less than 5.

The result on Serial Monitor:

COM6
Send
====== TEST START ====== Inside the WHILE loop: i = 0 Inside the WHILE loop: i = 1 Inside the WHILE loop: i = 2 Inside the WHILE loop: i = 3 Inside the WHILE loop: i = 4 ====== TEST END ========
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

※ NOTES AND WARNINGS:

  • When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop.
  • The following while loop loops forever:
while (true) { // statement(s) }
  • There are three ways to escape the while loop:
    • The condition of the while loop becomes false.
    • The execution of the code reaches a break statement inside the loop.
    • The execution of the code reaches a goto statement inside the loop, which jumps to a label located outside of the loop.

See Also

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

※ OUR MESSAGES