Welcome back to our programming tutorial using the Arduino IDE. Today we will deal with the while and do while loops.
You can take a look at the previous chapters of the course here:
- Arduino IDE: turn on LEDs using a button (if) #4.1
- Arduino IDE: the conditional construction IF #4
- Arduino IDE: arithmetic and logical operators #3
- Arduino IDE: variables, constants and macros #2
- How can I use Arduino IDE to write a program? #1
- Arduino IDE: what it is and how it works #0
When you try to solve a problem, you can come up with repetition structures while looking for the resolution algorithm.
In Arduino IDE you can address a repetition structure with the do… while loop, as follows:
1 2 3 |
do { instructions; while (condition); |
The sequence of statements between do and while is repeated many times, as long as the condition written on the while clause remains true: in other words the repetition ends when the condition is false.
The instructions of the do while loops are executed at least once, since the test is performed at the end of the group of instructions (in the condition). The condition check is performed at the end of each loop
There is a second iterative form that provides for the control of a condition prior to the execution of the instructions to decide the permanence or the exit of a cycle defined as pre-conditional repetition.
1 2 3 |
while(condition){ instructions; } |
The while loop is a structure that first tests whether the condition is true. if it is, the instructions included in the braces are executed. The instructions will be repeated as long as the condition is true. The repetition stops as soon as the condition becomes false, at the end of the loop.
The main difference from the do … while loop is in how the statements are executed. In the do … while loop the instructions are executed at least once, even if the condition is false since the condition will be verified at the end of the first loop, while the condition to access the while loops must necessarily be true since in the condition is verified before getting inside the loop.
Here is an example;
Previous articles:
- Arduino IDE: turn on LEDs using a button (if) #4.1
- Arduino IDE: the conditional construction IF #4
- Arduino IDE: arithmetic and logical operators #3
- Arduino IDE: variables, constants and macros #2
- Arduino IDE: how can I use Arduino IDE to write a program? #1
- Arduino IDE: what it is and how it works #0
Follow us to keep yourself updated with the news!