SEARCH W7R

Friday, April 06, 2012

The Do-While Loop (Java)

Of the questions I receive about loops, most are about the do-while loop. So, let me show you how the do-while loop works and when you would want to use it.

The Java syntax for a do-while loop is


do{

  /** code..
    * statement 1
    * statement 2
    **/

} while (condition);


The Do-While Cycle

1. Execute body of code 1 time from top to bottom.
2. check condition.
3. if condition is true, then go back to step 1
else exit the loop and execute lines of code that come after the loop.

THE GUMBALL MACHINE
How many times would the following do-while loop iterate?
double money=2.00;
do {
    //same as: money = money -0.25
    money-=0.25;
} while (money>=0.25);

Why would we ever want to use it instead of using a for loop, or while loop? In situations where if the condition is initially false, because in ordinary for and while loops the code would not be executed if the condition was initially false. Email me if you need additional help or have questions -w7rdotblogspot@gmail.com

No comments: