Web Statistics

while & do...while

Patience is not simply the ability to
wait - it's how we behave while we're waiting.

while

The while control allows a series of processes to be performed until a predetermined condition has been reached. There is a danger in this control where if the condition is never reached then the process contained in the block will be executed infinitely.

				
while (condition)
{
     code to be executed;
}	
				
			

In the example below we are examining the mathematical scenario, with a visual demonstration, of the 50/50 chance that a two-sided coin will land on heads if flipped 10 times. Thus while the flip count is less than 10 the process in the while block continues to be executed.

				
$headCount = 0;
$flipCount = 0;
while ($flipCount < 10) {
	$flip = rand(0,1);
	$flipCount ++;
	if ($flip){
		$headCount ++;
		echo "<div class=\"coin\">heads</div>";
	}
	else {
		echo "<div class=\"coin\">tails</div>";
	}
}
echo "<p>In $flipCount flips the coin landed on heads $headCount times!</p>";
				
			

tails

heads

tails

heads

tails

tails

tails

heads

heads

heads

 

In 10 flips the coin landed on heads 5 times!

The while block is only executed if the condition is true from the start, and continues to be true; however, what if the process in the while code block needs to be executed at least once no matter if the condition if true or false? In such scenarios the do...while control is used as a solution.

do...while

				
do
{
     code to be executed;
}
while (condition);
				
			

In the example below we are iterating through life's box of chocolates. Lets say that there are any number of chocolates in the box we are willing to share, but we want to take the box away if a white chocolate candy is eaten.

				
$candyCount = rand(1,20);
$eaten = 1;
$white = false;
do
{
	$eaten++;
	$chocolate = rand(0,1);
	if ($chocolate){
		echo "<div class=\"chocolate dark\">dark</div>";
	}
	else {
		$white = true;
		echo "<div class=\"chocolate white\">white</div>";
	}
}
while ($white == false && $eaten <= $candyCount);
echo "<p>You took the box away after $eaten chocolates were eaten!</p>";
				
			

dark

dark

dark

dark

dark

white

You took the box away after 6 of the 3 chocolates were eaten!

The while block is only executed if the condition is true from the start, and continues to be true; however, what if the process in the while code block needs to be executed at least once no matter if the condition if true or false? In such scenarios the do...while control is used as a solution.

Up Next

For and Foreach