Address Book: Loops

Jason Atkins, Alyce Brady, Pamela Cutter, R.C. McDowell, Kelly Schultz and Nathan Sprague 1997, 1999, 2002, 2009, 2015
Kalamazoo College, Kalamazoo, MI

The For Loop

A for loop is used to repeat a set of statements a number of times. In JavaScript, a for loop looks like this:

Syntactic Structure:
for ( init; test; step )
{
        actionStatements;
}
// code after the loop
Example:
for ( var i = 0; i < 10; i++ ) 
{
        output.innerHTML += "i = " + i + "<br>";
}
// code after the loop

The init expression initializes variables used in the loop, and is executed just once at the beginning of the loop. The test is a condition that is checked each time through the loop BEFORE we enter the loop body; if it is true the program executes the actionStatements in the loop body and if it is false it exits the loop. The step expression updates the loop variables for the next time through the loop – this is done immediately AFTER finishing the loop body and before the next evaluation of the test. One time through a loop is called an iteration.

Here's an English description of how the different parts of the loop work:

  1. Initialize the loop variables (using the init expression).
  2. Check the test. If the test fails, exit the loop (in other words, go to step 6).
  3. Perform the actionStatements in the loop body.
  4. Update the loop variables (using the step expression).
  5. Go to step 2.
  6. ... code after the loop ...
The number of times the actionStatements in the loop body are executed depends on the initial values in the loop, how they are changed, and the logical expression in the test.

Example: Simple Loop

The purpose of the following code fragment is to write the values of the loop variable, from 0 through 4, to a web page.

// write values of i, from 0 to 4, each on a separate line
for (var i = 0; i < 5; i++)
{
    output.innerHTML += "i = " + i + "<br>";
}

Try to identify the various parts of the loop. For example, what is the init expression, and what does it do? What is the test and when is it executed? What does the step expression do? What would this code fragment write to the web page? Ask the instructor or TA if you are unsure how to answer these questions!

Exercise 1 - Practice with Simple Loops
  1. In the head of the Address Book web page you created in the previous mini-lab, create another new function. This function will eventually print the contents of your address book, so give it a meaningful name that expresses this purpose. The function should take one parameter: the array of address book entries. For now, use the loop above as the body of the function. (This assumes that your page contains a div element with the id "output". If you gave your div element a different id, then use that id name instead.)
  2. In the body of the web page, locate the statements you wrote in the previous mini-lab that display the first and last people in your list. Add a call to your new function after those statements, passing it the appropriate parameter. Note that in the call, the parameter name should be the variable you created in the body, which is not necessarily the same name as you used in the function.

    Test your new function by saving and reloading the web page. The output should be the first and last entries from before, followed by the values of i from 0 to 4.

  3. Modify your function to print as many numbers as there are people in the list. To do this, use entryArray.length rather than the constant 5 as the upper bound for the loop index (where entryArray is whatever name you gave to your parameter). Now when you save and reload the web page, the output should be the first and last people, followed by the numbers from 0 to one less than the number of people in your list.

Another Example: Printing the Elements of an Array

One common use for a for loop is to step through the elements of an array. The example below is similar to the previous example, except that it has one extra line that uses the loop variable i as the array index into an address book array and writes the first five names to the web page. The expression entryArray[i] in the loop body refers to the single address entry (record) at index i in the array (if you used entryArray as your function parameter and name as the attribute for people's names). Each time through the loop, it will refer to a different entry in the array.

// display the names, each on a separate line
for (var i = 0; i < 5; i++)
{
    var entry = entryArray[i];
    output.innerHTML += "i = " + i + "; name = " + entry.name + "<br>";

}

We could have written the loop above without introducing the new entry variable, in which case we have referred to the person's name as entryArray[i].name.

Exercise 2 - Stepping Through Array Elements
  1. Modify the function you created in Exercise 1 to display the index numbers and peoples' names from your address book, as in the example above, but for everyone in the address book, not just the first 5 people. Test your function.
  2. Modify the function again to call your toString function for each entry, rather than just print the person's name. Test your modifications.
  3. Modify the function to drop the displaying of the index numbers. Test your modifications.
  4. Remove (or comment out) the lines in the body of your page from the previous mini-lab that created and printed a single entry, and also the lines that printed information for just the first and last people. Test your modifications.

Putting the Display in a Table

The output from the previous exercise is not very easy to read! We can display the address book information more neatly by using a table. However, the JavaScript code to generate a table is a bit tricky. Therefore, we have provided two incomplete functions, buildTable, and addTableRow, which together will display the list of addresses to a nicely formatted table. These two functions are included below, along with comments that describe their inputs. You will complete these functions in the exercise below.


//---------------
// buildTable
// This function builds or re-builds a table created in the BODY
// section of this page.  Each row of the table will contain an address
// from the addressArray, which must contain address book entry objects.
function buildTable(theTable, addressArray) 
{
    // Clear old contents of the table (if any).
    numRows = theTable.rows.length;
    for (var i = 0; i < numRows; i++)
    {
        // As the # of rows decreases, there is still a row 0.
        theTable.deleteRow(0);
    }

    // Add one entry in the address book to the table.
    // (Should be: Add each entry of the address book to the table.)
    // THE LINE BELOW SHOULD BE REPLACED WITH A
    //    FOR LOOP THAT CALLS addTableRow REPEATEDLY
    addTableRow(theTable, addressArray[0]);
 
}

//---------------- 
// addTableRow
// This function adds an address book entry to a new row in the table
// passed in as the first parameter.
// The second parameter should be a single entry from the address book. 
function addTableRow (theTable, addressBookEntry)
{
    // Which row is being added?  Depends on current # of rows in table.
    var nextRow = theTable.rows.length;
    var row = theTable.insertRow(nextRow);
    var cellNum = 0;

    // The cells in the row contain the person's name and address information.
    cell = row.insertCell(cellNum++);
    cell.innerHTML = addressBookEntry.name;
    cell = row.insertCell(cellNum++);
    cell.innerHTML = addressBookEntry.street;
    // NEED TO INSERT CELLS FOR THE CITY, STATE, AND ZIP

}

Exercise 3 - Formatting Information in a Table
  1. Copy and paste the functions above into the head section of your Address Book web page. Be sure to keep the comments; good comments are an important component of good programs.
  2. Copy the following table tags into the body of your page (above your output div, for example):
    <table border="1" style="margin-left: auto; margin-right: auto;" id="addressTable">
    </table>
    
    This is the table element that the buildTable function will insert entries into. (The margin-left and margin-right style attributes center the table on the page.)
  3. Comment-out or replace the call to your printing function from Exercises 1 and 2 with a call to the function buildTable, passing it the id of the table you just created (without quotation marks) and the array you created in the previous mini-lab. (As you've seen in previous mini-labs, you can use an element's id as if it were a variable name.)

    Load your page and check that it is working as expected. (Given that the buildTable and addTableRow functions are incomplete, what do you expect the page to do at this point?)

  4. Replace the "... SHOULD BE REPLACED BY ..." comment in the buildTable function with a for loop similar to that in Exercise 2. Within that loop, call the addTableRow function. What should you pass to it as parameters?

    Now that you have made this change, how do you expect your page to change? Load your page and check that it is working as expected.

  5. Replace the "NEED TO INSERT CELLS" comment in addTableRow with statements similar to the ones that print the various elements of a single address book entry, but now inserting them into cells in the table.

    Load your page and check that it is working as expected.

    You may look at the page on grading criteria for Mini-Labs 7 - 8 to see the breakdown of points given for this and the previous mini-lab.