Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write this loop better?

Tags:

c++

loops

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.

like image 594
regex4html Avatar asked Jul 10 '10 13:07

regex4html


People also ask

What is an example of a loop?

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.

What are the 3 types of loops?

The three types of loop control statements are: break statement. continue statement. pass statement.


1 Answers

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.

See also

  • Wikipedia/Do while loop

Pre-test and post-test loops

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.

References

  • MSDN: C++ Language Reference: The do-while Statement
  • MSDN: C# Language Reference: do
  • Java Language Specification §14.13: The do Statement

Related questions

  • Test loops at the top or bottom? (while vs. do while)
  • Is there ever a need for a do {…} while ( ) loop?
  • When is a do-while appropriate?
like image 50
polygenelubricants Avatar answered Sep 20 '22 15:09

polygenelubricants