7. All On Our Own (Math Error?)


#1

Hi all,

I wrote the following code:

<?php
	$i = 6;
	do {
		$i++;
		echo "<p>{$i} is less than 10!</p>";
	}	while ($i < 10);        
?>

The problem is, it returns the following:

7 is less than 10!
8 is less than 10!
9 is less than 10!
> 10 is less than 10!

The last line should not be echoed... Why is the iteration continuing AFTER 6 is no longer less than 10?

Thanks!


#2

Your loop is doing post-test not pre-test. That should start you on the path to enlightenment


#3

@sardawson as @dondabrera has pointed out you are doing a pretest when you write this

<?php
	$i = 6;
	do {
                //you increment the i here before you do anything
               //when i is 9 the code will increment it 10 print echo
               // the statement before it goes back into the condition block
               // to terminate
                $i++;
		echo "<p>{$i} is less than 10!</p>";
	}	while ($i < 10);        
?>

to fix it you need to do

<?php
	$i = 6;
	do {
		echo "<p>{$i} is less than 10!</p>";
		$i++;
	}	while ($i < 10);        
?>