do while

The do while loop is similar to the while except that the test is at the end of the loop. The do while always executes at least once.

Example 1: The code below will print 1 2 3 4 5 6 7 8 9 10

$i=1; 
do {
  echo $i.' ';
  $i++;
} while($i<=10);
Compare this to the while and for loops that printed the numbers from 1 to 10.

Example 2: The code below will print January February March April May
(January up to the current month)

$mth=1; //numeric representation of January
do {
  $date=mktime(0,0,0,$mth,1,2009); //January, any year
  echo date("F",$date).' ';
  $mth++;
}while($mth<=date("n"));

The do loop is often used in a search, we know that we have to look in the first position and we will search until we find what we are looking for.

Experiment: Write each of the following using a for, a while, and a do...while. Think about which was was easier for each example.

  1. Print the numbers from 10 to 1.
  2. Print the first five powers of 3. (3, 9, 27, etc.)
  3. Print the powers of 3 that are less than 100.
  4. Start with today and print the day of the week. Stop when you get back to today (Tuesday)
  5. Do the same thing with the months.
  6. Print the numbers of the Fibonacci sequence that are less that 100.

INDEX, Loops: Introduction, Loops: while, Loops: do while, Nested Loops
Next lesson: ArraysMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Loops: do while