Looping Construct: while and do-while

The while and do-while are looping constructs used to repeatedly execute a code block. A while loop is preferred over for statement when the number of iterations to be performed is indefinite. When you don’t know beforehand the number of times you have to loop, you use either while or do-while statement. The do-while loop’s code block is guaranteed to be executed at least once. The while loop’s code block may or may not be executed at all.

The while Statement

The general structure of the while loop is

while (anExpression) { // statements to be executed // if anExpression evaluates to true }

The expression used with the while statement in code above must be boolean – so it must evaluate to true or false.

If the condition evaluates to true, the code block is executed. After executing all the statements in the code block, the condition expression – anExpression in the sample above is evaluated once more. The loop terminates if the expression evaluates to false. Otherwise, the code block is executed one more time.

Consider the example below from our, by now favorite, Politician class –

123456789101112131415161718// we use while loop in this example// rather than a for loop// because we don’t know beforehand// when politicians will stop conning// and when hell might freeze over boolean hellFreezesOver = truewhile(hellFreezesOver) {    taxes++;  scamPeople(); } // the  above is an infinite loop// some external entity (may be spernatural)// needs to set the hellFreezesOver to false// to stop this loop

The do-while statement

The do-while statement is related to the while statement. The general structure of a do-while loop is

12345do { // code block while (anExpression) ; // notice the semicolon

As you can see, the condition expression is at the bottom of the loop. Therefore, the statements inside the do block are guaranteed to be executed once. After the first iteration, if the condition in the while statement is still true, another iteration is made. If the condition evaluates to false,  the loop exits.

Here is an example of where you might want to use do-while loop –

12345678910111213141516// the following is part of Politician class copsNotChasing = true; // rob people while cops are not chasing// cops are guaranteed not to chase// till the politician has robbed at least once// so do-while is preferred do {  robPeople();} while(copsNotChasing) ; // notice the ; // the above is an infinite loop// unless there is a divine intervention// and cops start chasing

Leave a comment

Your email address will not be published. Required fields are marked *