top of page

Programming structures: 'while'

This structure gives you a block of code while a condition is met it will repeat, if the condition is not met or no longer fulfilled it will stop repeating the code block. At the end of repeating the cycle, the code continues normally with what you have after the structure " while ". To use this instruction it is necessary to use variables and comparison operators. The "structure while " is used as follows: The block structure " while " is found in the section " Control " and has the following structure :

Example 1:

In this example we will make the LEDs flash red every second if we did not press any button, but while we press the 1 button the LEDs flash blue:

By not pressing any button or by pressing any button other than 1, the program block "to skip while " and only do what is outside of this, blinking the red LEDs. If pressing button 1 condition is met in the " while " it will do what is in the " do " by flashing LEDs in blue and stay there until the button is released.

do ... while

If the condition of the structure " while " is not true, not performed any time what's inside the " {} " because the comparison is made ​​at the beginning of the block. Sometimes we need that although the condition is not true, will realize at least once what is inside the " {} ", so that the structure is used "do ... while " which is very similar to the structure " while " the only difference is that as the comparison is made ​​at the end of the code block, allows us to at least make once it is inside the structure before the comparison is made. the block structure " do ... while " is found in the section " Control " and has the following structure:

Example 2

If the condition of the structure " while " is not true, it will not performed any at any time what's inside the " {} " because the comparison is made ​​at the beginning of the block. Sometimes we need that although the condition is not true, will realize at least once what is inside the " {} ", so that the structure uses the  "do ... while " which is very similar to the structure " while " the only difference is that as the comparison is made ​​at the end of the code block, allows us to at least make once it is inside the structure before the comparison is made. the block structure " do ... while " is found in the section " Control " and has the following structure:

By not pressing any button or any button other than 1, the program will jump to what is inside the block " do " and then continue with the rest of the program by flashing red LEDs. If pressing button 1 the condition is met will be in the " while " so the  LEDs will be in red and stay there until the button is released.

bottom of page