Java Programming Language (Loops: Nested loop)
Tags: java, tutorial, beginners, programming
Published: 2024-02-26 06:47:39

## Nested loop

Same as conditions, we can use a loop inside another loop. For example, 
```
public class Loops {
    public static void main(String[] args) {
        for (int person = 1; person <= 2; person ++) {
            for (int task = 1; task <= 3; task ++) {
                System.out.println("Person " + person + " completed task " + task);
            }
        }
    }
}
```
**Output**
```
Person 1 completed task 1
Person 1 completed task 2
Person 1 completed task 3
Person 2 completed task 1
Person 2 completed task 2
Person 2 completed task 3
```
Code always executes from top to bottom. If we think about this manner, The compiler first goes inside the outer `for` loop. Then it will execute the code inside the block until the loop condition is `false`. However, inside the loop block compiler found another `for` loop. Now the compiler will execute the code inside this inner `for` loop block until it terminates. Then the outer loop will go to the next iteration.

In this case, the outer loop will iterate two times and the inner loop will iterate three times. 
- First, while the outer loop is in it's first iteration the inner loop will iterate three times. 
- Once the inner loop terminates the outer loop will move on to it's second iteration. 
- In the second iteration the inner loop will reinitialise itself. As a result, while the outer loop is in it's second iteration the inner loop will again iterate over three times.
- After the inner loop terminates itself, the outer loop will also terminate as it does not meet the condition of outer loop.
- Then the compiler will execute the code from the next line.

There can be multiple nested loops and it can be performed with `while` loops as well. 

## break statement

`break` statement is generally used to terminate a block of code. Earlier we used `break` inside the `switch` statement in the [Conditions](https://dev.to/nihalislam01/java-programming-language-conditions-50i9) section to terminate the subsequent cases. In loops we can use `break` as well to terminate the iterations. 

```
public class Loops {
    public static void main(String[] args) {
        int count = 1;
        System.out.println("Counting to 3");
        while (true) {
            System.out.println("Count: " + count);
            if (count == 3) {
                break;
            }
            count++;
        }
    }
}
```
Here, on every iteration I am incrementing the `count` variable by 1. When the `count` becomes 3, the condition becomes `true` inside the `if` statement. As the compiler executes the `break` statement, it terminates the loop and goes to the next line after the loop.

**Output**
```
Counting to 3
Count: 1
Count: 2
Count: 3
```
## continue statement

`continue` statement is used to skip a particular iteration. Suppose, I want to print number 1 to 5 except number 3.
```
public class Loops {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue;
            }
            System.out.println(i);
        }
    }
}
```
When the code executes `continue` statement, it skips the current iteration and move on to the next iteration.
**Output**
```
1
2
4
5
```

## Appendix

while using nested loop, `break` or `continue` statement becomes ambiguous as it cannot figure out which loop it wants to terminate or skip. In these cases, we can use `label` to identify the loops. 
```
public class Loops {
    public static void main(String[] args) {
        // label
        outer:
        for (int i = 1; i <= 2; i++) {
            // label
            inner:
            for (int j = 1; j <= 3; j++) {
                if (j == 2) {
                    continue outer;
                }
                System.out.println("i = " + i + ", j = " + j);
            }
        }
    }
}
```
Here, we are labelling the loops before initialising so that we can specify the particular loop later. In the `continue` statement I am specifying which loop I want to skip when the condition meets.
**Output**
```
i = 1, j = 1
i = 2, j = 1
```
Find out what would happed if we skipped the inner loop instead of the outer loop here.

`label` can be used in `break` statements as well to terminate a certain loop.
```
public class Loops {
    public static void main(String[] args) {
        outer:
        for (int i = 1; i <= 2; i++) {
            inner:
            for (int j = 1; j <= 3; j++) {
                if (j == 2) {
                    break inner;
                }
                System.out.println("i = " + i + ", j = " + j);
            }
        }
    }
}
```
**Output**
```
i = 1, j = 1
i = 2, j = 1
```
Did you get the idea? Let me know in the comment section. 

Happy coding