Nested Loops
In Java, you can nest loops by placing one loop inside another. This is often used for complex iterations, such as working with two-dimensional arrays or for solving problems that involve nested structures. The most common types of nested loops are nested for
loops.
Example of Nested for
Loop - Multiplication Table:
public class NestedForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print(i * j + "\t");
}
System.out.println(); // Move to the next line after each row
}
}
}
In this example:
- The outer loop (
for (int i = 1; i <= 5; i++)
) iterates over the rows of the table. - The inner loop (
for (int j = 1; j <= 5; j++)
) iterates over the columns for each row. System.out.print(i * j + "\t");
prints the product ofi
andj
followed by a tab character.System.out.println();
moves to the next line after each row is printed.
The output of this program will be a simple multiplication table:
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
Example of Nested while
Loop - Pattern:
public class NestedWhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= i) {
System.out.print("* ");
j++;
}
System.out.println();
i++;
}
}
}
In this example, the outer while
loop controls the rows, and the inner while
loop controls the number of asterisks printed in each row. The output of this program will be:
*
* *
* * *
Example of Combination of Loop Types - while
Inside for
:
public class CombinationOfLoopsExample {
public static void main(String[] args) {
int i = 1;
while (i <= 3) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
i++;
}
}
}
This program produces the same output as the nested while
loop example.
Nested loops provide a way to handle more complex patterns and structures in your code. However, it's essential to maintain clarity and avoid excessive nesting to keep the code readable.