Understanding Java Nested Loops
Java supports the use of nested loops, which allow you to iterate through multiple layers of data. This feature is particularly useful when working with complex data structures or algorithms.
What are Nested Loops?
A nested loop is a loop that is placed inside another loop. The inner loop will iterate through its entire cycle for each iteration of the outer loop.
Example 1: Nested for Loop
In this example, we use a nested for loop to iterate through each day of a week for three weeks.
java
for (int i = 0; i < 3; i++) {
System.out.println("Week " + i);
for (int j = 0; j < 7; j++) {
System.out.println("Day " + j);
}
}
The output of this code will be:
Week 0
Day 0
Day 1
Day 2
Day 3
Day 4
Day 5
Day 6
Week 1
Day 0
Day 1
Day 2
Day 3
Day 4
Day 5
Day 6
Week 2
Day 0
Day 1
Day 2
Day 3
Day 4
Day 5
Day 6
Using Different Types of Loops
You can use different types of loops inside each other. For example, you can place a for loop inside a while loop.
java
int i = 0;
while (i < 3) {
System.out.println("Week " + i);
for (int j = 0; j < 7; j++) {
System.out.println("Day " + j);
}
i++;
}
This code will produce the same output as the previous example.
Creating Patterns with Nested Loops
Nested loops can be used to create patterns like full pyramids, half pyramids, and inverted pyramids. Here is an example of a program that creates a half pyramid pattern using nested loops.
java
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
The output of this code will be:
“`
*
* *
“`
Break and Continue Statements Inside Nested Loops
When using break and continue statements inside nested loops, it’s essential to understand how they affect the loop’s behavior.
- When a break statement is used inside the inner loop, it terminates the inner loop but not the outer loop.
- When a continue statement is used inside the inner loop, it skips the current iteration of the inner loop only. The outer loop is unaffected.
Here is an example that demonstrates the use of break and continue statements inside nested loops.
java
for (int i = 0; i < 3; i++) {
System.out.println("Week " + i);
for (int j = 0; j < 7; j++) {
if (j == 3) {
break;
}
System.out.println("Day " + j);
}
}
The output of this code will be:
Week 0
Day 0
Day 1
Day 2
Week 1
Day 0
Day 1
Day 2
Week 2
Day 0
Day 1
Day 2
Notice that the inner loop is terminated when j
reaches 3, but the outer loop continues to execute.