Welcome to Lesson 13!


Learning Objectives
By the end of today's lesson, you should be able to answer the following questions...
  • What is a counting loop?
  • What are the three important components of a counting loop?
  • What is a for loop and why was it designed?
  • How does a for loop differ from a while loop?
  • What is an off-by-one error and how can you avoid this type of error?
  • What is a nested loop?
  • How do you trace the output of a nested loop?
Announcements

  • Quiz 4 after the break
  • Don't forget Lab 6 due tomorrow
  • Advice on what CIS course to take next


Review Questions

Find a partner and answer the following question:

  • Write the following while loop as the equivalent for loop.

int count = 1;

while (count <= 10) {

    System.out.println(count);

    count++;

        } 

Applications of For Loops
  • We can use for loops in two ways:
  1. To repeat a task a specified number of times, where the task performed is not dependent on the counter.
    1. For example, making a bar graph (below).
  2. To repeat a task a specified number of times, where the task performed is dependent on the value of the counter.
    1. For example, summing a sequence of numbers (below).

Making Bar Graphs
  • We can use a counting loop to make a horizontal bar graph
  • Instead of displaying a number, we will display a series of "*" characters for the "bar"
  • Thus, all we need to change is the print statement:
    System.out.println(i);
    
    to become:
    System.out.println('*');
  • We can see this change in the following example:

Example Application That Displays a Bar Chart



int number = 0;
Scanner input = new Scanner(System.in);

System.out.print("Enter a number and I will show its"
             + " bar graph.\nEnter your number: ");
number = input.nextInt();

System.out.println("\nBar graph:");
       
for (int i = 0; i < number; i++) {
    System.out.print('*');
}
System.out.println();

Summing Numbers

  • One common looping task is to input a list of numbers and calculate their sum
  • For example, if we want to add the sum of the first four integers:
    sum = 1 + 2 + 3 + 4 = 10
  • As another example, we can add a list of 5 numbers:
    sum = 1 + 2 + 3 + 4 + 5 = 15
  • We can generalize our examples to sum from 0 to any number n.

Example Application to Sum a Sequence of Numbers

1
2
3
4
5
6
7
8
9
10
11
12

int number = 0;
int sum = 0;
Scanner input = new Scanner(System.in);

System.out.print("Enter the number to sum to: ");
number = input.nextInt();

for (int i = 1; i <= number; i++) {
    sum = sum + i; //using the counter as a value to add to my sum
}

System.out.println("The sum is: " + sum);

Activity 13.1: Tracing a Loop (10 pts)

In this exercise, we will trace the execution of the following for loop.

for (int i = 10; i <= 15; i++)
{
    if (i == 11 || i == 13 || i== 15)
        System.out.print("*");
    else
        System.out.print("!");
}

  • Find a partner. Then, open up a text editor such as Word or Notepad (Not Eclipse) and create a new document called tracing.doc or tracing.txt.
  • In the text editor write both your names at the top of the program.
  • Then, type what the output of the above for loop would be to the console.
  • Note, you should do this without running the code. 
  • Then, change the statement i <=15 to be i < 15.
  • Draw the output of the for loop with this alteration.
  • How is it different?
  • The instructor will be going over the examples so you can verify your answers and understanding.
  • Don't forget to upload your text document before the end of class.


More Loopy Errors

  • A common problem with counting loops is the off-by-one error
  • Finding the correct upper and lower bounds can be confusing
    • Should you start at 0 or 1?
    • Are you counting up to a number (<), or up to and including a number (<=)?
  • To understand the counting loop you need to count iterations.
  • For instance, the following loop executes b - a times:
    for (int i = a; i < b; i++)
  • However, the following loop is executed b - a + 1 times:
    for (int i = a; i <= b; i++)
  • The "+1" is the source of many errors
  • For example, to sum the numbers from 1 to 5, what is wrong with the following:
    
    public static void main(String[] arg)
    {
        int sum = 0;
        for (int count = 0; count < 5; count++)
        {
            sum += count;
        }
        System.out.println(sum);
    }
    
  • One way to visualize the "+1" error is by looking at a fence

Image source.

  • How many posts do you need for a fence with three sections?
  • It is easy to be "off-by-one" with problems like this
  • Forgetting to count the last value is sometimes called a fence-post error

Debugging Technique: Tracing Variables

  • One good way to discover loopy errors is to display the variables that are part of the loop
  • Tracing variables means watching their values change as the program executes
  • You can insert temporary output statements in your program to watch the variables, like:
    System.out.println("count= " + count + ", sum=" + sum);


Activity 13.2: Summing and Averaging (10 pts)

  • Let's write a program that uses a for loop to sum a list of numbers and computer their average.
  • Open up a new Eclipse project called Sum with a class named Sum.java.
  • First, declare and initialize 3 variables at the top of main:

  • Next, write a print statement to display a welcome message to the user:

Give me a list of numbers and I will compute their sum and average!

  • We will need to know the number of user inputs in advance so that we will know the ending condition of our for loop (in other words, how many numbers the user is planning to input).
  • Prompt the user to enter the quantity of numbers and read in the value to a variable named quantity:
    System.out.print("Enter the quantity of numbers: ");
    quantity = input.nextInt();
  • Next, we will write a for loop to read in that number of user inputs.
for (int i = 1; i <= quantity; i++) {
    //body of loop goes here
} 
  • Inside the loop we ask for each value and add it to the sum
    System.out.print("Enter value #" + i + ": ");
    number = input.nextDouble();
    sum = sum + number; //add number to our running total for the sum
  • The for loop will take care of adding up all of the numbers and storing the result in the sum variable.
  • Finally, below the for loop, we can print out the sum, and also compute the average.
  • Add a print statement to print the sum. Note that we will print both sum and average out to two decimal places.
System.out.printf("The sum of the numbers is: %.2f\n", sum);
  • Then, add a second print statement to print out the average.
  • Recall that the formula for calculating the average is:
  • Therefore, we can computer the average by dividing sum by quantity.

System.out.printf("The average of the numbers is: %.2f\n", (sum / quantity));

  • When your program is correctly displaying the sum and average as in the example output below, submit your work to Canvas.

Example Output


Your Program Should Look Identical to the Following:



Nested Loops

About Nested Loops
  • Some looping applications have loops nested within other loops
  • For example, you may use a nested loop to print a table of values
  • The following example shows a simple table created with nested loops
  • Let's follow the execution sequence before checking the result


Example of Nested Loops

1
2
3
4
5
6
7


for (int outer = 1; outer < 4; outer++)
{
    for (int inner = 1; inner < 4; inner++)
    {
            System.out.println(outer + " " + inner);
    }
}

Tracing the Variables

  • To understand a looping application, you need to trace the loop by hand
  • To trace the loop, write the variables used in the loop as headings across a page
  • On the first line under the headings, write the initial values
  • Execute the loop 3-5 times and record the values of the variables each time through the loop
  • Pay especial attention when entering the loop the first time and when ending the loop
  • You can slightly modify the computations if it helps to test the loop
  • Below is an annotated trace of the variables for the inner and outer loops
  • Note that the outer loop changes only after the inner loop is finished
Memory Screen 
 outer  inner  
  1  11 1
   21 2
   31 3
   4 (end of loop)   
  2  12 1
   22 2
   32 3
   4 (end of loop)   
  3  13 1
   23 2
   33 3
   4 (end of loop)   
  4 (end of loop)     
  • By analogy, nested loops are like an odometer on a car
  • The inner loop is like the digit to the right on an odometer
  • The numbers to the right loop completely before the number to the left increments by one

Nested Loop Example: Drawing Squares
  • Another example of a nested loop is to draw a square using stars ("*")
  • Remember our bar graph example with the for loop?
  • Copy and paste the following code into your Netbeans Loopy program, compile and run it.
    package loopy;

    /**
    *
    * @author Jennifer Parrish
    */
    import java.util.Scanner;

    public class Loopy {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {

    int size = 0;
    Scanner input = new Scanner(System.in);

    System.out.print("Enter a number and I will show its"
    + " bar graph.\nEnter your number: ");
    size = input.nextInt();
    System.out.println();

    for (int row = 1; row <= size; row++)
    {
    System.out.print("*");
    }
    System.out.println();

    }

    }

  • Now, let's alter the program to contain a nested for loop.
  • We will place another for loop inside the first one.
  • The nested loop makes the bar graph print in 2D.
  • The code for drawing a square consists of two loops, one nested inside the other:
    for (int row = 1; row <= size; row++)
    {
        for (int col = 1; col <= size; col++)
        {
            System.out.print("*");
        }
        System.out.println();
    }
    
  • The code is easier to read from the inside out
  • The inner loop draws a line of characters across the screen from left to right
  • At the end of the inner loop we print a newline to end the line of characters
  • The outer loop controls the number of lines to draw
  • Note how the inner loop is indented to make the structure clear
  • The inner loop is controlled by the outer loop, which is why it is indented
  • The inner loop in turn controls other statements, which ends up indenting yet again
  • Whenever you type an opening brace ({) you should indent the next character
  • Whenever you type a closing brace (}) you should remove the indentation (outdent)

Example Program to Draw Squares

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

package loopy;

/**
*
* @author Jennifer Parrish
*/
import java.util.Scanner;

public class Loopy {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

int size = 0;
Scanner input = new Scanner(System.in);

System.out.print("Enter a number and I will print a square."
+ "\nEnter your number: ");
size = input.nextInt();
System.out.println();

for (int row = 1; row <= size; row++)
{
for (int col = 1; col <= size; col++)
{
System.out.print("*");
}
            
System.out.println();
         }
}

}
  • We can make the square hollow by using an if statement inside the inner loop to decide when to print characters
  • Develop test conditions that allow the characters to print only at the start and end of the columns and rows
  • Use an else clause to print spaces when not printing characters
  • Another example of a nested loop is to draw a triangle, which we explore in the next exercise

Activity 13.3: Tracing a Nested Loop (10 pts)

In this exercise we explore how nested loops work by tracing the execution of a loop in a program. Part of the trace will involve use of the Boolean "or" (||) operator we discussed last class.

Specifications

  • Find a partner.
  • Take out a piece of paper, put your name on it and draw a grid like this:

rowcol#12345
11 21*    
21 2 32**   
  3     
  4     
  5     
  • Leave extra room for the col column as shown. The right hand area is for drawing the shape where the row and column headings match the row and col variables of the program.
  • For the code snippet listed below, trace the loop variables and write the values of the loop variables on the paper as your trace progresses for 5 rows. In addition, draw on your paper the shape printed by the nested loops in the program. Do NOT run the program.
  • You can see the trace for the first few entries in the grid above. As you trace the program, cross out the col entries as you update them, as shown. However, make each row change start on a new row so that the graph on the right lines up with the row entries.
1
2
3
4
5
6
7
8
9
10
11
12
13
14

for (int row = 1; row <= 5; row++)
{
    for (int col = 1; col <= row; col++)
    {
        if (col == 1 || row == col || row == 5)
        {
            System.out.print("*");
        }
        else
        {
            System.out.print(".");
        }
    }
    System.out.println();
}
  • Draw the output into the text box under the activity on Canvas.
  • The instructor will trace it on the board when everyone is finished.


Wrap Up

  • With your partner, answer the questions from today's learning objectives

Upcoming Assignments
  • Assignment 13 due Tuesday at 11:20am on Canvas
  • Lab 6 due tomorrow at midnight

~Have a Great Weekend!~