Skip to content
C

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. What 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.

2. Why 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.

3. Real-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.

4. Syntax

java
for (int i = 0; i < outerLimit; i++) { for (int j = 0; j < innerLimit; j++) { // inner loop code } }

5. Example Program

java
public 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=2

6. Key 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.