Nested loops in Java mean placing one loop inside another loop. The inner loop runs completely for each iteration of the outer loop. Nested loops are commonly used for working with patterns, tables, matrices, and multi-dimensional data.
for, while, and do-whileThe most common nested loop structure is a for loop inside another for loop.
// General syntax of nested for loop
for(int i=1;i<=rows;i++){
for(int j=1;j<=columns;j++){
System.out.print("* ");
}
System.out.println();
}
Printing a simple square star pattern using nested loops.
// Java program to print a 5x5 star pattern
class NestedLoops{
public static void main(String[] args){
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
System.out.print("* ");
}
System.out.println();
}
}
}
The outer loop controls the number of rows. The inner loop prints stars in each row. After the inner loop finishes, a new line is printed, creating a square pattern.
* * * * * * * * * * * * * * * * * * * * * * * * *
Change the number of rows to simulate the Java logic in real-time!
row and colwhile loops instead of for