Breaking Out of Loops with the BREAK Statement

Chapter 6 #121 - Martha's CIS 52

ASSIGNMENT/EXPLANATION

"Both while and for statements incorporate a built-in test expression with which you can end a loop. However, the breat statement enab les you to break out of a loop based on the results of additional tests. This can safeguard agains error." (121) The danger often arises when the counter variable comes from user input. This may result in an effort to use a negative number, or a string, either of which would not be desirable: division by zero results in an answer of "undefined", and a string can not be divided mathematically. (WHAT HAPPENS?)

Exercise

4000 divided by 1 is...4000
4000 divided by 2 is...2000
4000 divided by 3 is...1333.3333333333
4000 divided by 4 is...1000
4000 divided by 5 is...800
4000 divided by 6 is...666.66666666667
4000 divided by 7 is...571.42857142857
4000 divided by 8 is...500
4000 divided by 9 is...444.44444444444
4000 divided by 10 is...400

CODE

<?php 
for ($counter=1; $counter <= 10; $counter++) {
$temp = 4000/$counter;
echo "4000 divided by ".$counter." is...".$temp."<br />";
}
?>