Chapter 4 - Repetition Control Structures

By: Albert Ritzhaupt

 

 


Chapter Topics

Why Repetition? 

All the control structures up to now have one element in common - they only occur one time.  It is very rare that a usefully computer program will only do something one time.  That is why we have what we call repetition control structures.  A repetition control structure will execute a block of code a number of times based on some condition.  In the world of programming, we generally will use two types of repetition control structures: counting and conditional.  We commonly refer to repetition control structures as loops.  This chapter will focus on a few of the looping controls structures available to us in PHP and provide simple examples.

back to top

The While Loop 

To start, we will first explore the while loop.  The loop is considered a conditional loop because it bases the number of iterations the a condition.  The syntax for the while loop is straight-forward and can be seen in the diagram below.

while(condition)
{
statement
}

The while loop is considered a pre-test loop because it first tests the condition, and if the condition is true, it executes the statement.  It will continue to execute the statement until the condition is false.  It is important to note that if the condition never becomes false, the statement will continue to execute.  This is what we refer to as an endless loop, and is generally, bad programming practice.  Be sure your while loop will always stop executing.

If the condition is false the first time the while loop condition is tested, it will never execute the statement.  This is why we say that a while loop has a zero to N range, where N is some number.   The while loop can be used for a number of purposes, such as reading and writing to a file as will be discussed in Chapter 7.  Lets do an example to make sure you understand how the while loop works.

Assume that you want a drop down menu for the next 15 years on your HTML form.  If you were to hard code this just using HTML, it would be time consuming and error prone.  We will use a while loop to do this for us as shown in the example below.

Example 1
<html>
<form>
<select name="year">
<?php
$currentYear=2005; // initial year
while($currentYear <= 2020)
{
echo "<option value='$currentYear'>";
echo $currentYear;
$currentYear++; // adds one to year
}
?>
</select>
</form>
</html>

First the variable $currentYear is assigned the integer value 2005 - the year this e-book was written.  After, the while loop condition is tested.  Since, 2005 is less than 2020, the condition is true and the statements within the while loop are executed.  First, the option value is assigned the value, then the display text for the drop down is displayed.  After the the information is displayed using the echo statement, the $currentYear variable is incremented by 1, and the condition is tested once again.  This process continues until the variable $currentYear is greater than 2020.  The program above is a simple example of the use of a while loop and is shown in the link below. 

>>Program Example 1

back to top

The Do-While Loop

The next repetition control structure that we need to explore is the do-while loop, which is also considered a conditional loop.  The do-while loop works much the same way the while loop works with one fundamental differences: the do-while loop is a post test loop. In contrast, the while loop first tested the condition, then executed the statement after determining the condition was true; hence, the phrase pre test loop.  The syntax for the do-while loop can be seen in the figure below.

do{
statement
}while(condition)

As you can see by looking at the syntax of the do while loop, the statement occurs before the condition.  This should help you remember the difference between a while loop and a do while loop.  Since the statement is executed before the condition is tested, the do while loop is guaranteed to execute at least once.  This is why we say that a while loop has a one to N range, where N is some number.  Regardless of whether the condition is true or false, it will execute at least once, which proves to be important for certain tasks.

To make sure you understand the do while loop, lets create a simple program.  We will create a program to list a series of numbers from 1 to N, where N is a number parameter provided by the user.  The code for the example can be seen below.

Example 2
<html>
<?php
$limit=$_POST['limit'];
?>
<form action="example2.php" method="POST">

List To: <input name="limit"><br>
<input type="submit" value="list">
</form>
<br><br>
<b>List of Numbers</b>:
<?php
$i=1;
do{
echo "$i ";
$i++;
}while($i <= $limit)
?>
</html>

A link to the program is below.  You should pay special attention to the fact that regardless of the input, the program will, at minimum, print one.  This is because the do while loop always executes at least once.  Try different number and see that the program lists all the to that number you provided, inclusive.  Keep in mind that no limit is placed on the size of the number.  If you entered a very large number, the program would execute for a long time and probably freeze up your browser.

>>Program Example 2

back to top

The For Loop

The final loop that we are going to investigate in this chapter is the for loop - our first and only counting loop.  The for loop is called a counting loop because it executes  a number of times (which is still a condition) rather than on a condition.  The for loop is an extremely handy control structure for working with lists of information, such as arrays.  The for loop is a little more sophisticated than the while and do while loop.  It also has a more complicated syntax as can be seen in the figure below.

for(initialization; condition; increment)
{
statement
}

The for loop has three different sections to worry about in addition to the statement: initialization, condition, and increment.  The initialization section is for initializing a variable to a starting value and is the first thing executed.  The initialization only executes once.  The condition is similar to the other loops.  The for loop would be considered a pre test loop.  Finally, there is the increment section which is executed after the statement.  Both the condition and increment are executed multiple times based on the number of times the for loop will execute.

The for loop is best understood by a solid example.  For our example, lets assume you want to create a program to find the summation of a given number (meaning the sum of 1 to N).  The for loop is perfectly suited for a summation.  Look at the code in the example below.

Example 3
<html>
<?php
$num=$_POST['num'];
?>
<form action="example3.php" method="POST">

Number: <input name="num"><br>
<input type="submit" value="Summation">
</form>
<br><br>

<?php
echo "<b>The Sum of $num is</b>: ";
$sum=0;
for($i=1; $i <= $num; $i++)
{
$sum = $sum + $i;
}
echo $sum;

?>
</html>

Notice that the program uses the variable $num as the summation value.  After the variable is captured from the user, the program sets the variable $sum to zero then enters the for loop.  The for loop does the following:

  1. Sets the variable $1 to zero
  2. Checks the condition of whether $i is less than or equal to $num
  3. Executes the statement "$sum = $sum + $i;"
  4. Increments the variable $i
  5. Continues steps 2 - 4 until the condition is false

This is a simple algorithm to exemplify the application of a for loop.  Make sure you understand how the for loop works now; otherwise, when we get to more complicated topics, you will not be able to follow.  An example of this program can be linked to below.

>>Program Example 3

back to top

Nesting Loops

Just as we nested if statements in the previous chapter, we can next loops in this chapter.  Nesting loops is common practice in computer programming for a number of reasons, such as working with multidimensional arrays which we will address in Chapter 6.  The syntax for nesting loops is shown in an example below using for loops.

Example 4
<html>

<?php

for($i=0; $i < 10; $i++)
{
for($j=1; $j <= 10; $j++)
{
$total = $i + $j;
echo "$total ";
}
echo "<br>";
}

?>
</html>

The outer loop in this program executes from 0 to 9.  The inner loop of this program executes from 1 to 10.  Each time the outer loop is executed, the inner loops starts over again.  As a result, this program simply prints a sequence of numbers that increments by one each time the inner loop is executed.  The program can be linked to by the link below:

>>Program Example 4

back to top

Continue Statement

The final topic in this chapter is the continue statement, which can be used in conjunction with loops.  The continue statement  to skip the rest of the current loop, continue at a specified condition , and then the beginning of the next iteration. A picture of this idea can be seen in the diagram figure below.

As shown in the example, the continue statement executes and the flow of control is moved N levels above in the nesting structure, inclusive.  The continue statement will not be necessary for any of the programs in this text, but is useful when programming in the real world. 

back to top

Your Fourth Program

This section will provide the steps for you to create your fourth PHP program.  You are going to create a simple PHP program to print a dynamic table as given a number of rows and columns provided by a user.

  1. First create a file named "fourth.html" in a directory that is recognized by the web server. The file should contain the following information:

    <html>
    <h3>Rows x Columns</h3>
    <form action="program4.php" method="post">
    Rows: <input name="rows"><br>
    Colons: <input name="cols"><br>

    <input type="Submit" value="Create">

    </form>

    </html>

  2. Now let's create the source code for the program.  Create a file named "program4.php" in the same directory as "fourth.html".  The file should contain the following information:

    <html>
    <?php
    //captures variables
    $rows=$_POST['rows'];
    $cols=$_POST['cols'];
    echo "<h2>$rows x $cols Matrix</h2>";
    echo "<table align='center' border='1'>";
     //nested for loops
    for($i=0; $i < $rows;$i++)
    {
    echo "<tr>";

    for($j=0; $j < $cols;$j++)
    {
    echo "<td>";
    echo " ";
    echo "</td>";
    }
    echo "</tr>";
    }
    echo "</table>";

    ?>

    Note:  The source code must appear exactly as it does here.  Otherwise, you will likely run into syntax errors. 
  3. After you have created the file and put the information into the files, save your work, and change the permissions of the files to:

    prompt$: chmod 704 fourth.html
    prompt$: chmod 705 program4.php

  4. Open the URL to the location where you saved the file (fourth.html) and you should be able to submit values.

    It is probably a good idea to keep the matrix within 100 x 100.  If you select anything larger, it will take a long time to process.  After you submit row and column values, count to make sure your program worked.  Notice that the outer loop handles the rows, while the inner loop handles the columns.  Make sure you fully understand loops and nested loops before you continue.

Congratulations! You have completed the fourth chapter. You can now take the online assessment, complete the fourth activity, and move to the next chapter. 

>>Take the Online Quiz

back to top

Activity 4

Create a simple form and use PHP to populate a drop down list that includes the values 1 to 25.  Title this form Factorial Calculator and provide the name number for the drop down list.  Also, include a submission button on the form.  The form should point the action attribute to factorial.php and the method should be POST.

Create a PHP program named factorial.php to accept the number from the HTML form.  Use a for loop to calculate the factorial of the number.  The factorial of a number is the multiplication of all the numbers from 1 to N, where N is the number provided.  For example,

N = 5

The factorial of N is therefore 5 * 4 * 3 * 2 * 1 = 120. 

The for loop should initialize the incremented variable to 1.  Use the summation example to aide in this activity.

back to top

Chapter References 

back to top

 

Copyright 2005 Albert Dieter Ritzhaupt. All Rights Reserved.