Popular Searches
Popular Course Categories
Popular Courses

Applying Nested Loops

Applying Nested Loops

Loops and Iteration in Java

Applying Nested Loops in Java

Course: Core Java Training

Topic: Applying Nested Loops

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Nested Loops

A nested loop is a loop placed inside another loop. The outer loop controls the main repetition, while the inner loop performs additional repetitions during each iteration of the outer loop.

Nested loops are useful when a program needs to process rows and columns, work with multidimensional arrays, print patterns, generate multiplication tables, compare values, or create combinations of elements.

Java supports nested for loops, nested while loops, nested do-while loops, and combinations of different loop types.

Why Are Nested Loops Important?

  • Process two-dimensional arrays and matrices.
  • Print star patterns, number patterns, and geometric shapes.
  • Generate multiplication tables.
  • Compare elements in arrays.
  • Generate combinations of numbers and characters.
  • Perform repetitive tasks involving rows, columns, or multiple conditions.
  • Develop a foundation for algorithms such as matrix operations and basic sorting techniques.

2. Syntax of Nested Loops

A nested for loop places one for loop inside the body of another loop.

for (initialization1; condition1; update1) {
    // Outer loop statements

    for (initialization2; condition2; update2) {
        // Inner loop statements
    }
}
Component Description
Outer loop Controls the main repetition, such as the number of rows.
Inner loop Controls repeated operations within each outer iteration, such as the number of columns.
Initialization Sets the starting value of a loop-control variable.
Condition Determines whether the loop should continue.
Update Changes the loop-control variable after an iteration.
Loop body Contains the instructions that execute during each iteration.

The outer loop begins first. Whenever its condition is true, Java executes the inner loop. The inner loop completes its iterations before the outer loop moves to its next iteration.

3. Understanding the Execution Flow

Consider a program in which the outer loop runs twice and the inner loop runs three times during each outer iteration.

public class NestedLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 2; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.println("i = " + i + ", j = " + j);
            }
        }
    }
}

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3

Step-by-Step Execution

  1. The outer loop initializes i to 1.
  2. The inner loop initializes j to 1.
  3. The program prints the current values of i and j.
  4. The inner loop increments j until its condition becomes false.
  5. After the inner loop finishes, the outer loop increments i.
  6. The inner loop starts again, with j initialized to 1 for the new outer iteration.
  7. When the outer condition becomes false, the nested loop terminates.

The outer loop executes twice, and the inner loop executes three times per outer iteration. Therefore, the print statement executes \(2 \times 3 = 6\) times.

4. Printing a Rectangle Using Nested Loops

Nested loops are frequently used to print rows and columns of characters. The outer loop controls the rows, while the inner loop controls the number of characters in each row.

Example: Rectangle of Stars

public class RectanglePattern {
    public static void main(String[] args) {
        for (int row = 1; row <= 4; row++) {
            for (int column = 1; column <= 5; column++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output:

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

The outer loop executes four times, producing four rows. The inner loop prints five stars in each row. The System.out.println() statement moves the cursor to the next line after each row.

5. Printing an Increasing Triangle

When the number of inner-loop iterations depends on the outer-loop variable, nested loops can generate triangles and other patterns.

Example: Increasing Star Triangle

public class StarTriangle {
    public static void main(String[] args) {
        for (int row = 1; row <= 5; row++) {
            for (int column = 1; column <= row; column++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output:

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

The first row contains one star, the second row contains two stars, and each subsequent row contains one additional star. The inner-loop condition column <= row determines how many stars appear in each row.

6. Printing a Decreasing Triangle

A decreasing triangle can be created by starting the outer loop at the maximum row count and reducing its value after each iteration.

public class DecreasingTriangle {
    public static void main(String[] args) {
        for (int row = 5; row >= 1; row--) {
            for (int column = 1; column <= row; column++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output:

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

The outer loop counts down from 5 to 1. Because the inner loop uses the current row value as its limit, each new row contains fewer stars.

7. Printing Number Patterns

Nested loops can print numbers instead of characters. The expression inside the inner loop determines which number appears in each position.

Example A: Repeating the Row Number

public class RepeatedNumberPattern {
    public static void main(String[] args) {
        for (int row = 1; row <= 5; row++) {
            for (int column = 1; column <= row; column++) {
                System.out.print(row + " ");
            }
            System.out.println();
        }
    }
}

Output:

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Example B: Increasing Numbers in Each Row

public class NumberTriangle {
    public static void main(String[] args) {
        for (int row = 1; row <= 5; row++) {
            for (int column = 1; column <= row; column++) {
                System.out.print(column + " ");
            }
            System.out.println();
        }
    }
}

Output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

In the first example, the program prints the outer-loop variable. In the second example, it prints the inner-loop variable. This small change produces a different pattern.

8. Generating Multiplication Tables

Nested loops can generate multiplication tables for several numbers. The outer loop selects the number, and the inner loop calculates its multiples.

public class MultiplicationTables {
    public static void main(String[] args) {
        for (int number = 1; number <= 3; number++) {
            System.out.println("Table of " + number);

            for (int multiplier = 1; multiplier <= 5; multiplier++) {
                System.out.println(
                    number + " x " + multiplier + " = " +
                    (number * multiplier)
                );
            }

            System.out.println();
        }
    }
}

Output:

Table of 1
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5

Table of 2
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

Table of 3
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15

This program displays the multiplication tables for 1, 2, and 3, with each table containing five results.

9. Applying Nested Loops to Two-Dimensional Arrays

A two-dimensional array stores data in rows and columns. In Java, it is represented as an array whose elements are themselves arrays. Nested loops allow a program to visit every element in the structure.

Example: Display a Matrix

public class MatrixExample {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        for (int row = 0; row < matrix.length; row++) {
            for (int column = 0; column < matrix[row].length; column++) {
                System.out.print(matrix[row][column] + " ");
            }
            System.out.println();
        }
    }
}

Output:

1 2 3
4 5 6
7 8 9

The expression matrix.length returns the number of rows. The expression matrix[row].length returns the number of elements in the current row. Using the current row's length also supports jagged arrays, in which rows can have different lengths.

10. Calculating the Sum of Matrix Elements

A nested loop can process every matrix element and add each value to a running total.

public class MatrixSum {
    public static void main(String[] args) {
        int[][] values = {
            {10, 20, 30},
            {40, 50, 60},
            {70, 80, 90}
        };

        int sum = 0;

        for (int row = 0; row < values.length; row++) {
            for (int column = 0; column < values[row].length; column++) {
                sum += values[row][column];
            }
        }

        System.out.println("Total sum: " + sum);
    }
}

Output:

Total sum: 450

The outer loop selects each row, while the inner loop visits each element in that row. Every value contributes to the sum exactly once.

11. Using Nested while Loops

A nested loop does not have to use the for statement. A while loop can be placed inside another while loop when repetition is controlled by conditions.

public class NestedWhileExample {
    public static void main(String[] args) {
        int row = 1;

        while (row <= 3) {
            int column = 1;

            while (column <= 2) {
                System.out.println(
                    "Row " + row + ", Column " + column
                );
                column++;
            }

            row++;
        }
    }
}

Output:

Row 1, Column 1
Row 1, Column 2
Row 2, Column 1
Row 2, Column 2
Row 3, Column 1
Row 3, Column 2

The inner counter is initialized inside the outer loop so that it starts at 1 for every new row. If the counter were initialized only once before the outer loop, the inner loop might not execute again after its first completion.

12. Using Nested do-while Loops

A do-while loop executes its body at least once before checking its condition. Nested do-while loops can be used when each repetition level must execute at least once.

public class NestedDoWhileExample {
    public static void main(String[] args) {
        int row = 1;

        do {
            int column = 1;

            do {
                System.out.print("* ");
                column++;
            } while (column <= 3);

            System.out.println();
            row++;
        } while (row <= 2);
    }
}

Output:

* * *
* * *

Both loops check their conditions after executing their bodies. This behavior distinguishes do-while loops from for and while loops, which check their conditions before the next iteration.

13. Using break in Nested Loops

The break statement terminates the nearest enclosing loop. When it appears inside an inner loop, it normally exits only that inner loop, allowing the outer loop to continue.

public class NestedBreakExample {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int column = 1; column <= 5; column++) {
                if (column == 3) {
                    break;
                }

                System.out.println(
                    "Row " + row + ", Column " + column
                );
            }
        }
    }
}

Output:

Row 1, Column 1
Row 1, Column 2
Row 2, Column 1
Row 2, Column 2
Row 3, Column 1
Row 3, Column 2

For each row, the inner loop stops when the column reaches 3. The outer loop then starts the next row.

Exiting an Outer Loop with a Labeled break

Java supports labeled statements. A labeled break can terminate an outer loop directly from inside an inner loop.

public class LabeledBreakExample {
    public static void main(String[] args) {
        search:
        for (int row = 1; row <= 3; row++) {
            for (int column = 1; column <= 3; column++) {
                if (row == 2 && column == 2) {
                    System.out.println("Target found");
                    break search;
                }
            }
        }

        System.out.println("Search completed");
    }
}

Output:

Target found
Search completed

Labeled breaks are useful when a condition must end multiple levels of nested loops. Use them sparingly so that the control flow remains readable.

14. Using continue in Nested Loops

The continue statement skips the remaining statements in the current iteration of the nearest enclosing loop and proceeds to its next iteration.

public class NestedContinueExample {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int column = 1; column <= 3; column++) {
                if (column == 2) {
                    continue;
                }

                System.out.println(
                    "Row " + row + ", Column " + column
                );
            }
        }
    }
}

Output:

Row 1, Column 1
Row 1, Column 3
Row 2, Column 1
Row 2, Column 3
Row 3, Column 1
Row 3, Column 3

The program skips column 2 on every row but continues processing the remaining columns.

15. Generating Pairs and Combinations

Nested loops can combine values from two sequences to generate pairs. This technique is useful for checking combinations, testing possible selections, and generating simple schedules.

public class NumberPairs {
    public static void main(String[] args) {
        for (int first = 1; first <= 3; first++) {
            for (int second = 1; second <= 2; second++) {
                System.out.println(first + ", " + second);
            }
        }
    }
}

Output:

1, 1
1, 2
2, 1
2, 2
3, 1
3, 2

The outer loop has three possible values, and the inner loop has two possible values. The program therefore generates six ordered pairs.

16. Comparing Array Elements with Nested Loops

Nested loops can compare elements with other elements in an array. This approach is useful for learning comparison algorithms, finding duplicate values, and understanding basic searching techniques.

Example: Find Duplicate Values

public class DuplicateFinder {
    public static void main(String[] args) {
        int[] numbers = {4, 7, 2, 7, 9, 4};

        for (int i = 0; i < numbers.length; i++) {
            for (int j = i + 1; j < numbers.length; j++) {
                if (numbers[i] == numbers[j]) {
                    System.out.println(
                        "Duplicate value: " + numbers[i]
                    );
                    break;
                }
            }
        }
    }
}

Output:

Duplicate value: 4
Duplicate value: 7

The inner loop begins at i + 1, so each element is compared only with the elements that follow it. This avoids comparing an element with itself. The inner break stops checking further matches for the current outer element after a duplicate is found.

17. Understanding Nested Loop Performance

The number of operations performed by nested loops depends on the number of iterations in each loop. If both loops execute approximately n times and the body performs constant-time work, the total number of executions is approximately n².

Outer Iterations Inner Iterations per Outer Loop Total Inner Executions
2 3 6
4 4 16
5 10 50
10 10 100

When both loops iterate over input collections of size n, the time complexity is often O(n²). This is common in pairwise comparisons and some basic sorting algorithms. Actual performance depends on the loop bounds, the operations inside the body, and any early exits.

Performance Best Practices

  • Avoid repeating expensive calculations inside the inner loop when their results can be calculated once.
  • Reduce inner-loop iterations when the problem allows it.
  • Consider more efficient data structures or algorithms when processing large collections.
  • Do not assume every nested loop is inefficient; evaluate the actual workload.
  • Use profiling and measurement to identify bottlenecks in larger applications.

18. Common Mistakes When Applying Nested Loops

Mistake Problem Solution
Reusing a local variable name in overlapping scopes Redeclaring a loop variable with the same name can cause a compilation error. Use distinct names such as row and column.
Incorrect inner-loop condition The loop executes too many or too few times. Check the starting value, stopping condition, and update.
Not resetting an inner while-loop counter The inner loop may not run again on subsequent outer iterations. Initialize the inner counter inside the outer loop when it needs to restart.
Missing update statement The loop may become infinite. Ensure the control variable changes appropriately.
Incorrect array boundaries Accessing an invalid index may cause ArrayIndexOutOfBoundsException. Use valid conditions such as row < matrix.length and column < matrix[row].length.
Incorrect placement of output statements Pattern output may appear on one line instead of separate rows. Place System.out.println() after the inner loop when each outer iteration represents a row.
Misunderstanding break An ordinary break exits only the nearest enclosing loop. Use a labeled break when necessary or restructure the logic.
Unnecessary nested loops Extra iterations can make the program slower. Consider whether a single loop or a more efficient algorithm can solve the problem.

19. Practical Project: Student Marks Matrix Analyzer

This project uses nested loops to process marks for multiple students across multiple subjects. It calculates each student's total and average marks.

Project Code

public class StudentMarksMatrix {
    public static void main(String[] args) {
        int[][] marks = {
            {80, 75, 90},
            {85, 88, 92},
            {70, 78, 82}
        };

        for (int student = 0; student < marks.length; student++) {
            int total = 0;

            for (int subject = 0; subject < marks[student].length; subject++) {
                total += marks[student][subject];
            }

            double average = (double) total / marks[student].length;

            System.out.println("Student " + (student + 1));
            System.out.println("Total Marks: " + total);
            System.out.printf("Average Marks: %.2f%n", average);
            System.out.println();
        }
    }
}

Expected Output

Student 1
Total Marks: 245
Average Marks: 81.67

Student 2
Total Marks: 265
Average Marks: 88.33

Student 3
Total Marks: 230
Average Marks: 76.67

Project Explanation

  • The two-dimensional array stores marks for three students across three subjects.
  • The outer loop selects each student.
  • The inner loop processes all subject marks for that student.
  • The total variable accumulates the student's marks.
  • The average is calculated by dividing the total by the number of subjects.
  • The program displays the total and average before moving to the next student.

Project Enhancements

  • Add more students and subjects.
  • Calculate the highest mark in each subject.
  • Calculate the class average for each subject.
  • Identify the student with the highest total marks.
  • Display the results in a formatted table.
  • Validate that marks fall within the permitted range.

20. Practice Exercises

  1. Print a rectangle containing five rows and six columns of stars.
  2. Print an increasing right-angled triangle using numbers.
  3. Print a decreasing triangle with five rows.
  4. Generate multiplication tables from 1 to 10 using nested loops.
  5. Create a two-dimensional array and display every element.
  6. Calculate the sum of all elements in a two-dimensional array.
  7. Find the largest element in each row of a matrix.
  8. Print the main diagonal of a square matrix.
  9. Generate every possible pair from two integer arrays.
  10. Find duplicate elements in an array using nested loops.
  11. Use nested while loops to print a rectangle of numbers.
  12. Use break to exit an inner loop when a target value is found.
  13. Use a labeled break to exit an outer loop from inside an inner loop.
  14. Calculate how many times the inner loop executes when the outer loop runs four times and the inner loop runs five times per outer iteration.
  15. Modify the Student Marks Matrix project to display the highest and lowest marks for each student.

21. Interview Questions and Answers

Q1. What is a nested loop in Java?

A nested loop is a loop written inside the body of another loop. The inner loop executes its iterations during each iteration of the outer loop.

Q2. Why are nested loops used?

They are used for multidimensional arrays, patterns, multiplication tables, combinations, and comparisons between collection elements.

Q3. How many times does the inner loop execute?

If the outer loop runs m times and the inner loop runs n times during each outer iteration, the inner body executes m × n times, assuming no early exits.

Q4. Can different types of loops be nested in Java?

Yes. Java allows combinations such as a for loop inside a while loop or a do-while loop inside a for loop.

Q5. What is the difference between an outer loop and an inner loop?

The outer loop controls the main repetition, while the inner loop performs additional repetitions within each outer iteration.

Q6. What happens when break is used inside an inner loop?

An ordinary break terminates the nearest enclosing loop. The outer loop can continue unless it is separately terminated.

Q7. Can continue be used inside nested loops?

Yes. An unlabeled continue skips the remaining statements in the current iteration of the nearest enclosing loop. A labeled continue can target a labeled outer loop.

Q8. Why should an inner while-loop counter sometimes be initialized inside the outer loop?

It needs to be reset if the inner loop must start again from its initial value for every outer iteration.

Q9. What is the time complexity of two nested loops?

If both loops execute approximately n times and the inner body takes constant time, the time complexity is commonly O(n²).

Q10. How are nested loops used with two-dimensional arrays?

The outer loop usually iterates through rows, and the inner loop iterates through the elements of the current row.

Q11. What is a labeled break?

A labeled break terminates the statement associated with a specified label, allowing an inner loop to exit an outer loop.

Q12. Are nested loops always inefficient?

No. Nested loops are appropriate for tasks that require processing combinations, rows and columns, or pairs of elements. Performance depends on the input size and the work performed.

Q13. What is a jagged array in Java?

A jagged array is a two-dimensional array whose rows can have different lengths. Using matrix[row].length allows the inner loop to process each row correctly.

Q14. How can infinite loops be prevented?

Check that each loop has a suitable initialization, condition, and update. Make sure the control variables change so the conditions eventually become false when termination is expected.

22. Quick Revision Checklist

  • Understand the definition and purpose of nested loops.
  • Know how the outer and inner loops execute.
  • Practise star patterns, triangles, and number patterns.
  • Use nested loops to generate multiplication tables and combinations.
  • Process two-dimensional and jagged arrays safely.
  • Understand nested for, while, and do-while loops.
  • Know the difference between ordinary and labeled break statements.
  • Understand how continue affects the nearest loop.
  • Calculate iteration counts and estimate time complexity.
  • Identify incorrect boundaries, missing updates, and other common errors.
  • Practise a real-world project involving rows, columns, and calculations.

23. Additional Learning Resource

For further study, explore the official Java tutorial on the for statement and enhanced for loop. It explains loop initialization, termination conditions, updates, and iteration through arrays and collections.

24. Conclusion

Nested loops are an essential Core Java concept for tasks that require multiple levels of repetition. By combining outer and inner loops, developers can process matrices, generate patterns, calculate multiplication tables, compare array elements, and solve a wide range of programming problems. Understanding execution order, loop boundaries, control statements, and performance helps you write accurate, efficient, and maintainable Java programs.

Continue learning with the Core Java Training course at JustAcademy, register through the course demo registration page, or visit the JustAcademy homepage.

whatsapp