Control Flow · Lesson 32 of 150
Nested Loops
A nested loop is a loop placed inside another loop. The inner loop completes all its repetitions for every single repetition of the outer loop.
1 min read
01What are Nested Loops?
A nested loop is a loop placed inside another loop. The inner loop completes all its repetitions for every single repetition of the outer loop.
02Why is it used?
Some problems naturally involve two levels of repetition — like printing a grid of rows and columns, or comparing every student with every other student. Nested loops handle this two-level repetition.
03Real-Life Example
Think of a teacher checking attendance for every student in every classroom of a school. For each classroom (outer loop), the teacher goes through every single student (inner loop) before moving to the next classroom.
04Syntax
javafor (int i = 0; i < outerLimit; i++) { for (int j = 0; j < innerLimit; j++) { // inner loop code } }
05Example Program
javapublic class NestedLoopDemo { public static void main(String[] args) { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { System.out.println("i=" + i + ", j=" + j); } } } }
Output:
i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=206Key Points to Remember
- The inner loop finishes completely before the outer loop moves to its next step.
- Nested loops are commonly used for pattern printing and working with 2D arrays.
- Be careful with nested loops on large data — they can slow a program down significantly since work multiplies.