Java Nested Loops with Examples (original) (raw)

Last Updated : 11 Jan, 2024

A Nested loop means a loop statement inside another loop statement. That is why nested loops are also called “loop inside loop“.

**Nested For loop

for ( initialization; condition; increment ) {
for ( initialization; condition; increment ) {
// statement of inside loop
}

// statement of outer loop
}

**Nested While loop

while(condition) {
while(condition) {
// statement of inside loop
}

// statement of outer loop
}

**Nested Do-While loop

do{
do{
// statement of inside loop
}
while(condition);

// statement of outer loop
}
while(condition);

**Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level.

**Hybrid Java Nested Loops

do{
while(condition) {
for ( initialization; condition; increment ) {
// statement of inside for loop
}

// statement of inside while loop

}

// statement of outer do-while loop
}while(condition);

Below are some examples to demonstrate the use of Nested Loops:

Examples of Java Nested Loops

**Example 1: Below program uses a nested for loop to print a 2D matrix.

Java

import java.io.*;

class GFG {

`` public static void print2D( int mat[][])

`` {

`` for ( int i = 0 ; i < mat.length; i++) {

`` for ( int j = 0 ; j < mat[i].length; j++)

`` System.out.print(mat[i][j] + " " );

`` System.out.println();

`` }

`` }

`` public static void main(String args[]) throws IOException

`` {

`` int mat[][] = { { 1 , 2 , 3 , 4 },

`` { 5 , 6 , 7 , 8 },

`` { 9 , 10 , 11 , 12 } };

`` print2D(mat);

`` }

}

Output

1 2 3 4 5 6 7 8 9 10 11 12

**Example 2: Below program uses a nested for loop to print all prime factors of a number.

Java

import java.io.*;

import java.lang.Math;

class GFG {

`` public static void primeFactors( int n)

`` {

`` while (n % 2 == 0 ) {

`` System.out.print( 2 + " " );

`` n /= 2 ;

`` }

`` for ( int i = 3 ; i <= Math.sqrt(n); i += 2 ) {

`` while (n % i == 0 ) {

`` System.out.print(i + " " );

`` n /= i;

`` }

`` }

`` if (n > 2 )

`` System.out.print(n);

`` }

`` public static void main(String[] args)

`` {

`` int n = 315 ;

`` primeFactors(n);

`` }

}