Boucle while

Description

Les boucles while ("tant que" en anglais) bouclent sans fin, et indéfiniment, jusqu'à ce que la condition ou l'expression entre les parenthèses ( ) devienne fausse. Quelque chose doit modifier la variable testée, sinon la boucle while ne se terminera jamais. Cela peut être dans votre code, soit une variable incrémentée, ou également une condition externe, soit le test d'un capteur.

Syntaxe

while(expression){ // tant que l'expression est vraie // instructions à effectuer }

Paramètres

  • expression: Une instruction (booléenne) C qui renvoie un résultat VRAI ou FAUX.

Exemple

void setup() { Serial.begin(9600); Serial.println("====== TEST START ======"); int i = 0; while (i < 5) { // tant que la variable est inférieur à 5 // fait quelque chose 5 fois de suite... Serial.print("Inside the WHILE loop: i = "); Serial.println(i); i++; // incrémente la variable } 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  

※ Remarque:

  • 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.

Voir Également

ARDUINO BUY RECOMMENDATION

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

※ OUR MESSAGES

  • We are AVAILABLE for HIRE. See how to hire us to build your project
  • Any suggestion, correction, and translation? please email us at ArduinoGetStarted@gmail.com, We appreciate it
  • We mainly keep improving the references in English. See English version of this page for the latest update.