Loops

 Introduction.  At many points in time it is important to get different blocks of code to execute repeatedly.  This is called looping.  For example, maybe you want to add up the total cost of the items in a shopping basket maybe you want to search through every record in a table to modify those that live in a particular zip code maybe you want to compute a factorial maybe you want to work through a list to find the average of some numbers on and on Obviously, this list can continue to grow ad infinitum. There are two main types of loops depending on how the programmer wants the looping to occur.  These are described briefly in the following table.

 For Loops While Loops Basic Syntax for (\$index = \$start; \$index <= \$end; \$index++) { //  block to execute repeatedly } while (condition) { //  block to execute repeatedly } \$start can be set by programmer \$end can be set by programmer \$index++ can actually be changed to other sizes the condition can be anything like we used on the previous page and many other things used when there is clearly an index of importance with a starting value, ending value and increment sizes more likely to be used when the condition to be met isn't as clear as some numerically incrementing criteria

 I think that when each type of looping structure is more likely to be used is best seen through a variety of examples.  We will work two examples on this page, but we will develop many more throughout the course of our semester.Our first example involves developing a form for user input.  We will ask the user how many integers in a sequence, 1, 2, ... n, they want to sum.  Then we will compute the sum and display the result using a processing script. We will first work this problem using a for loop, then with a while loop in order to demonstrate how both approaches can be used to solve the same problem.  We will demonstrate the advanatages of one approach over another in later pages. You should call the form page sum_of_n.html.

 Number Form

How many of the first N integers do you want to sum?

 Now the processing script follows.  It should be called handle_sum_of_n.php.

 Sum of the First N Integers

The sum of the first \$txt_upper_limit integers is \$total

"; ?>

 Now we will rework the problem using a while loop.  We need a new form page in order to get it to post to a different processing script.  You should call this file sum_of_n_while.html.

 Number Form

How many of the first N integers do you want to sum?