Back

Activity 2.9 Nested Loops

divider

Introduction

Activity 2.9

Nested Loops

Topics

  • Introduction to Nesting Loops
  • Demo: Grid

Introduction to Nesting Loops

Nested loops are tools for handling tasks that involve multiple layers of repetition. By placing one loop inside another, you can manage complex operations.

Each time the outer loop runs, the inner loop completes all its iterations.

Demo: Grid

for (int row = 1; row <= 5; row++)
{
for (int col = 1; col <= 3; col++)
{
System.out.print("(Row " + row + ", Col " + col + ")\t");
}
System.out.println();
}
(Row 1, Col 1) (Row 1, Col 2) (Row 1, Col 3)
(Row 2, Col 1) (Row 2, Col 2) (Row 2, Col 3)
(Row 3, Col 1) (Row 3, Col 2) (Row 3, Col 3)
(Row 4, Col 1) (Row 4, Col 2) (Row 4, Col 3)
(Row 5, Col 1) (Row 5, Col 2) (Row 5, Col 3)

Nested For Loop Animation

Tips for Working with Nested Loops

1. The "Inner Loop Runs Completely" Rule

The single most important concept to nail down is the flow of control:

For every single iteration of the outer loop, the inner loop will execute its entire range, from start to finish.

Clock Analogy:The hour hand (outer loop) only moves one time for every twelve complete revolutions of the minute hand (inner loop).

Tips for Working with Nested Loops

2. Differentiate the Control Variables

Students often struggle when the inner loop's condition depends on the outer loop.

Always use different variable names (e.g., i and j, or row and col). Also, explicitly state what each variable controls.

  • Outer Loop Variable (i or row): Almost always controls the row number or the group/set being processed.
  • Inner Loop Variable (j or col): Almost always controls the column number or the individual item within that group.

Tips for Working with Nested Loops

3. Visualize Output with the print/println Distinction

When teaching pattern generation, students often confuse when to stay on the same line versus moving to the next. Use this rule for pattern printing:

  • The inner loop uses System.out.print() to put elements side-by-side (building the column/row content).
  • The line of code immediately after the inner loop (but still inside the outer loop) uses System.out.println() to force the cursor to the next row.

Tips for Working with Nested Loops

4. Pre-Calculate the Total Iterations

Before writing any code, you should be able to calculate the total number of times the inner block of code will execute. This helps you catch infinite loops or off-by-one errors early.

  • For fixed loops, the total complexity is the product of the number of iterations: Total = Outer loop iterations * Inner loop iterations
  • If the outer loop runs 10 times and the inner loop runs 5 times, the code inside the inner loop runs 10 * 5 = 50 times.

'F' → Fullscreen

Objectives

  • icon Writing and tracing nested loops
  • icon Generating tables
divider

Activity Tasks

  • icon Create a new project named 2-9-Nested-Loops.
  • icon Complete each task individually.

Task 1: Multiplication Table

Program.java
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
// ANSI Color Codes
final String GREEN_TEXT = "\u001B[32m";
final String RED_TEXT = "\u001B[31m";
final String WHITE_TEXT = "\u001B[37m";
Scanner input = new Scanner(System.in);
System.out.println("--- Demo 1 - Multiplication Table ---");
System.out.print("Enter the size of the table: ");
int size = input.nextInt();
// Column Headers
for (int i = 0; i <= size; i++)
{
// Omit braces for single-line code blocks
// Exclude zero at top left
if (i == 0)
System.out.print("\t");
else
System.out.print(GREEN_TEXT + i + "\t");
}
System.out.println(); // Move to next row
for (int num1 = 1; num1 <= size; num1++)
{
// Left column
System.out.print(GREEN_TEXT + num1 + "\t" + WHITE_TEXT);
// Body for each row
for (int num2 = 1; num2 <= size; num2++)
{
System.out.print(num1 * num2 + "\t");
}
System.out.println(); // Move to next row
}
input.nextLine(); // Consume newline
System.out.print("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
}
}

Task 2: Multi-Room Game Demo

  • icon For brevity, I omitted a significant amount of game logic from this demo. Feel free to fill in the gaps as you like.
Program.java
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
44 collapsed lines
// ANSI Color Codes
final String GREEN_TEXT = "\u001B[32m";
final String RED_TEXT = "\u001B[31m";
final String WHITE_TEXT = "\u001B[37m";
Scanner input = new Scanner(System.in);
System.out.println("--- Demo 1 - Multiplication Table ---");
System.out.print("Enter the size of the table: ");
int size = input.nextInt();
// Column Headers
for (int i = 0; i <= size; i++)
{
// Omit braces for single-line code blocks
// Exclude zero at top left
if (i == 0)
System.out.print("\t");
else
System.out.print(GREEN_TEXT + i + "\t");
}
System.out.println(); // Move to next row
for (int num1 = 1; num1 <= size; num1++)
{
// Left column
System.out.print(GREEN_TEXT + num1 + "\t" + WHITE_TEXT);
// Body for each row
for (int num2 = 1; num2 <= size; num2++)
{
System.out.print(num1 * num2 + "\t");
}
System.out.println(); // Move to next row
}
input.nextLine(); // Consume newline
System.out.print("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
boolean playing = true;
int keys = 0;
String choice;
System.out.println("\n--- Demo 2 - Multi-Room Game Demo ---");
System.out.println(RED_TEXT + "Work-in-progress. Expect bugs!" + WHITE_TEXT);
while (playing)
{
System.out.println(GREEN_TEXT + "-Main Hallway-" + WHITE_TEXT);
System.out.println("1) Kitchen");
System.out.println("2) Bathroom");
System.out.println("3) Bedroom");
System.out.println("4) Quit Demo");
System.out.print("-> ");
choice = input.nextLine();
if (choice.equals("1"))
{
while (!choice.equals("2"))
{
System.out.println(GREEN_TEXT + "-Kitchen-" + WHITE_TEXT);
System.out.println("1) Search cupboards");
System.out.println("2) Leave");
System.out.print("-> ");
choice = input.nextLine();
if (choice.equals("1"))
{
System.out.println("Found a key in the cupboard!");
keys++;
}
else if (choice.equals("2"))
{
System.out.println("Exiting kitchen.");
}
else
{
System.out.println("Invalid input.");
}
}
}
else if (choice.equals("2"))
{
System.out.println(GREEN_TEXT + "-Bathroom-" + WHITE_TEXT);
// Demo code omitted
}
else if (choice.equals("3"))
{
System.out.println(GREEN_TEXT + "-Bedroom-" + WHITE_TEXT);
// Demo code omitted
}
else if (choice.equals("4"))
{
playing = false;
}
else{
System.out.println("Invalid choice.");
}
}
}
}
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
--- Demo 1 - Multiplication Table ---
Enter the size of the table: 5
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
Press enter to continue...
--- Demo 2 - Multi-Room Game Demo ---
Work-in-progress. Expect bugs!
-Main Hallway-
1) Kitchen
2) Bathroom
3) Bedroom
4) Quit Demo
-> 1
-Kitchen-
1) Search cupboards
2) Leave
-> 1
Found a key in the cupboard!
-Kitchen-
1) Search cupboards
2) Leave
-> 2
Exiting kitchen.
-Main Hallway-
1) Kitchen
2) Bathroom
3) Bedroom
4) Quit Demo
-> 4
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Describe one programming task that cannot be reasonably accomplished with a single loop but requires a nested loop to manage. Why is the nested structure essential for that specific task?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete