I have a code that does something like this:
while (doorIsLocked()) {
knockOnDoor();
}
openDoor();
but I want to be polite and always knock on the door before I open it. I can write something like this:
knockOnDoor();
while (doorIsLocked()) {
knockOnDoor();
}
openDoor();
but I'm just wondering if there's a better idiom that doesn't repeat a statement.
A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.
The three types of loop control statements are: break statement. continue statement. pass statement.
You can use a do-while
instead of a while-do
loop:
do {
knockOnDoor();
} while (doorIsLocked());
openDoor();
Unlike a while-do
loop, the do-while
executes the body once before checking the termination condition.
The do-while
loop -- sometimes called just a do
statement -- in C/C++/C#/Java/some others is what is known as a "post-test" loop: the terminating condition is checked after each iteration. It loops while
a condition is true
, terminating immediately once it's false
.
Pascal has a repeat-until
loop, which is also a "post-test" loop; it loops while a condition is false
, terminating immediately once it's true
.
Fortran's do-while
loop on the other hand is a "pre-test" loop: the terminating condition is checked before each iteration. In C/C++/Java/C#/some others, while-do
and for
loops are also "pre-test" loops.
Always check language reference when in doubt.
do-while
Statementdo
do
Statementwhile
vs. do while
) do {…} while ( )
loop?do-while
appropriate?If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With