Nested Loops in Java
In programming, a loop is used to repeat a block of code multiple times based on a given condition. A nested loop in Java refers to placing one loop inside another, allowing you to perform more complex iterations. Nested loops are commonly used in scenarios where you need to perform operations on a multi-dimensional data structure, such as a 2D array, or when dealing with tasks that involve repeating an action multiple times within another repeated action.
A nested loop is simply a loop within another loop. The inner loop runs completely for each iteration of the outer loop. This means that the inner loop’s code block will be executed multiple times for each single execution of the outer loop.
Java provides three types of loops:
All of these loops can be nested inside each other, allowing for flexible control over iterations.
Consider the scenario where you want to print a pattern like a multiplication table or a grid. To do this, you can use nested loops to handle the rows and columns of the table.
for
LoopsA nested for
loop is a loop inside another for
loop. The outer loop controls the number of rows, while the inner loop controls the columns.
for
Loops
public class NestedForLoopExample {
public static void main(String[] args) {
int rows = 5;
int columns = 5;
// Outer loop for rows
for (int i = 1; i <= rows; i++) {
// Inner loop for columns
for (int j = 1; j <= columns; j++) {
System.out.print(i * j + "\t"); // Multiply row and column numbers
}
System.out.println(); // Move to the next line after each row
}
}
}
Explanation:
for (int i = 1; i <= rows; i++)
) iterates over the rows.for (int j = 1; j <= columns; j++)
) iterates over the columns.Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
while
LoopsA nested while
loop works in a similar way to a for
loop but with the condition-based iteration.
while
Loops
public class NestedWhileLoopExample {
public static void main(String[] args) {
int rows = 3;
int columns = 4;
int i = 1; // Outer loop control variable
// Outer while loop for rows
while (i <= rows) {
int j = 1; // Inner loop control variable
// Inner while loop for columns
while (j <= columns) {
System.out.print(i + j + "\t"); // Sum of row and column indices
j++;
}
System.out.println(); // Move to the next line after each row
i++;
}
}
}
Explanation:
while
loop iterates over the rows.while
loop iterates over the columns for each row.Output:
2 3 4 5
3 4 5 6
4 5 6 7
do-while
LoopsA nested do-while
loop is another variant of a loop within a loop where the inner loop runs at least once, regardless of the condition.
do-while
Loop Printing a Star Pattern
public class NestedDoWhileLoopExample {
public static void main(String[] args) {
int rows = 5;
int i = 1;
// Outer do-while loop for rows
do {
int j = 1;
// Inner do-while loop for columns
do {
System.out.print("* ");
j++;
} while (j <= i); // Inner loop runs i times
System.out.println(); // Move to the next line after each row
i++;
} while (i <= rows); // Outer loop runs rows times
}
}
Explanation:
do-while
loop runs for each row.do-while
loop runs a number of times equal to the current row number (i.e., i
).Output:
*
* *
* * *
* * * *
* * * * *
Nested loops are often used when working with multi-dimensional arrays, grids, matrices, or tables. Below are some common use cases:
When dealing with matrices, you often need to use nested loops to iterate over rows and columns to perform operations like matrix multiplication or matrix addition.
public class MatrixMultiplicationExample {
public static void main(String[] args) {
int[][] matrixA = {{1, 2}, {3, 4}};
int[][] matrixB = {{5, 6}, {7, 8}};
int[][] result = new int[2][2]; // Resultant matrix
// Outer loop for rows
for (int i = 0; i < 2; i++) {
// Inner loop for columns
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
// Print the result matrix
System.out.println("Result of Matrix Multiplication:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(result[i][j] + "\t");
}
System.out.println();
}
}
}
Explanation:
Output:
Result of Matrix Multiplication:
19 22
43 50
When working with 2D arrays (arrays of arrays), nested loops are a must. You use the outer loop for iterating over the rows and the inner loop for iterating over the columns.
public class Traverse2DArrayExample {
public static void main(String[] args) {
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Using nested for loops to traverse the 2D array
for (int i = 0; i < array.length; i++) { // Outer loop for rows
for (int j = 0; j < array[i].length; j++) { // Inner loop for columns
System.out.print(array[i][j] + "\t");
}
System.out.println();
}
}
}
Explanation:
Output:
1 2 3
4 5 6
7 8 9