Nested Structures

Things To Do First

Things To Do Later

Nested Loops

We talked about nested selection statements in chapter 3. Similarly, you can nest two (or more) loops. Trace the code in listing 5.7 in Chapter 5.9 to see how it works.

The example below shows how nested loops execute. Note that the inner loop completes all its iterations for each iteration of the outer loop.

for (int i=1; i<=5; i++) {            // start of outer loop <------+
   System.out.println("\ni is now " + i);   //                      |
   for(int j=1; j<=4; j++) {                // start of inner loop  |
      System.out.print("  j = " + j);       //                      |
   }                                        // end of inner loop    |
}                                     // end of outer loop <--------+

We will trace this code in class, but if you're trying this on your own, you can match your manual tracing's output with the actual output below:

i is now 1
  j = 1  j = 2  j = 3  j = 4
i is now 2
  j = 1  j = 2  j = 3  j = 4
i is now 3
  j = 1  j = 2  j = 3  j = 4
i is now 4
  j = 1  j = 2  j = 3  j = 4
i is now 5
  j = 1  j = 2  j = 3  j = 4

Nested loops are often used to handle or display tabular information. The trick to making this work is to remember that usually the outer loop prints a row, and the inner loop prints each column in a row.

Exercises

[solutions]

1. What's the output of each of the following programs:

Example a:

public class ExerciseA {

    public static void main(String[] args) {

        for (int i=0; i<=5; i++) {
            System.out.print(i + ":  ");
            for (int j=1; j<3; j++) {
                System.out.print((i * j) + " ");
            }
            System.out.println();
        }
    }
}

Example b:

public class ExerciseA {

    public static void main(String[] args) {

        for (int i=0; i<=5; i++) {
            System.out.print(i + ":  ");
            for (int j=3; j>0; j--) {
                System.out.print((i * j) + " ");
            }
            System.out.println();
        }
    }
}

2. Use nested loops to print the following table:

2  3  4  5  6
3  4  5  6  7
4  5  6  7  8
5  6  7  8  9
6  7  8  9 10

3. Use nested loops to print a square of asterisks (*) with a given number of rows and columns. E.g. if the user enters 3, it would print:

***
***
***

If the user enters 5, it would print:

*****
*****
*****
*****
*****

4. You and three of your classmates go bowling and want to track and display your results for three games. Write a program that prompts the user to enter the score for each player for each of the three games, and then displays the average score for each player. Sample output is shown below (prompts in navy blue, inputs in red, output in black):

Scores for Player 1
Game 1: 200
Game 2: 205
Game 3: 210
  Average Score: 205.00
	
Scores for Player 2
Game 1: 198
Game 2: 182
Game 3: 201
  Average Score: 193.67
	
Scores for Player 3
Game 1: 252
Game 2: 267
Game 3: 281
  Average Score: 266.67
	
Scores for Player 4
Game 1: 207
Game 2: 243
Game 3: 199
  Average Score: 216.33

Nesting Other Structures

You can also nest selections inside loops, and loops inside selections. For example, determine the output of each of the following code segments:

// first code segment
for (int i=1; i<=10; i++)
{
	if (i%2 == 0)
		System.out.println(i);
}
// second code segment
System.out.println("Enter the high number:");
int high = Integer.parseInt(keysIn.readLine());
System.out.println("Enter the low number:");
int low = Integer.parseInt(keysIn.readLine());
if (high > low)
{
	for (int i=low; i<=high; i++)
		System.out.println(i);
} else
	System.out.println("Your low value must be smaller " +
		"than your high value!");

Exercises

[solutions]

1. Modify the temperature conversion table from an earlier lesson: The user enters the starting value and the ending value for the Fahrenheit values to convert into Celsius values. If the user enters a start value that is greater than the ending value, display the table from highest to lowest, instead of lowest to highest.

2. A user wants to find out the grade points for each of their final grades this term. Write a program that allows the user to enter any number of final grades that they want, and display the grade points according to Sheridan's Grading System.

Additional Exercises

[solutions]

1. Use nested loops to print a triangle with a given number of rows. E.g. if the user enters 3, it would print:

*
**
***

If the user enters 5, it would print:

*
**
***
****
*****

2. Break-even Analysis: When you are manufacturing a product, you need to know how many units you should produce in order to break even. For example, say you are making widgets. You pay $1000 a week to rent your manufacturing building, and it costs you $50 to manufacture one widget (raw materials and labour). It also costs an average of $10 per widget to sell and market your widgets. The rent is what we call a "fixed" cost, because it's always the same from week to week (or whatever period of time for which you are analyzing). Whether you make 1 widget or 1000 widgets, you are still going to pay $1000 a week in rent. Costs such as the manufacturing and selling costs are "variable" costs, because they vary, depending on how many widgets you make. If you make one widget, it will cost you $50 + $10 = $60 in variable costs, but if you make 1000 widgets, it will cost you (50 + 10) * 1000 = $60,000 in variable costs.

Which is better, to make 1 widget or to make 1000 widgets? It looks like it will cost a lot ot make 1000 widgets! Once you have a selling price for your product, you can calculate how much revenue you will gain (or lose!). For example, if we sell one widget for $200, will we make a profit selling only one widget or selling 1000 widgets?

Since it costs $60 + $1000 = $1060 to make one widget, and we will make $200 selling that widget, we'll end up with a loss of $1860! Not very good! Will we make a profit selling 1000 widgets? It costs $60,000 + $1000 = $61,000 to make 1000 widgets, and we will make $200 * 1000 = $200,000 in revenue from 1000 widgets. That means we've made a profit of $140,000! Not bad!

Do we make money or lose money if we manufacture 10 widgets? It will cost (50 + 10) * 10 + 1000 = $1600 to make 10 widgets and we will make $200 * 10 = $2000 in revenue. This means a profit of $400.

An important part of this process is knowing your break-even point. This is the point at which you stop making a loss and start making a profit. Write a program that prompts the user to enter the manufacturing costs, selling costs, fixed costs, and selling price. Your program should then calculate how many units it will take to reach the break-even point.

3. Write a program that calculates the average final grade for a student who's taken some unknown number of courses. The final grade entered must be greater than or equal 0: if the user enters a negative grade, display an error message and ask again.

4. Do questions 5.8, 5.10, 5.16, 5.18, 5.24, and 5.30 at the end of Chapter 5.