Updated March 27, 2023
Introduction to Nested Loop in Java
The loops that consist of another loop inside it as a nest-like structure are built, and the outer loop monitors the number of executions of the inner loop, loops working in such structure where is known as nested loop. It is also known as a loop inside the loop.
Syntax of Nested Loop in Java
Following are the different syntax:
1. Nested For loop
for(initialize;cond1;increment/decrement)
{
for(initialize;cond2;increment/decrement)
{
//body of loop2
}
//body of loop1
}
2. Nested While loop
while(cond1)
{
while(cond2)
{
// body of loop2
}
//body of loop1
}
3. Nested Do-while loop
do{
do{
//body of loop 2
}while(cond2)
//body of loop 1
}while(cond1
4. Nested heterogenous loop
Nesting of the loop has no limitations that only similar types of loops can be nested. We can nest any loop inside any other loop, such as while inside for loop or while loop inside the do-while loop and all other possible combinations are all applicable.
for(initialize;cond1;increment/decrement)
{
while(cond2){
//body of loop2
}
// body of loop1
}
Flowchart
Explanation:
In the above flowchart, first, when we enter the body of the program, a statement such as initialization or print statements get executes. Once a loop is found, the program checks for the condition for the outer loop; if it returns true, it enters the loop; otherwise, the loop is ended, and the rest of the program’s statements after loop executes.
Once it enters the outer loop and encounters the inner loop, variables are initialized if any is present, followed by checking the condition for inner loop if it returns true program enters into the inner loop; otherwise, go back to end of Loop1 and perform increment/decrement for executing Loop1 again.
In case cond2 returns true, Loop2 statements get executed, and the counter variable gets incremented/decremented. This procedure is repeated a number of times, and then the program exits from Loop2, then Loop1 and move to statements present after the loop.
How Nested Loop works in Java?
Every loop consists of below 3 things inside them:
- Initialization: This step refers to initializing the value of the counter.
- Condition: This condition refers to the comparison that needs to be true for continuing the execution of the loop.
- Increment/Decrement of counter: This refers to the operation to be performed on the counter once one flow of loop ends.
In the case of nested loops, the above three steps are checked for each loop inside it. Thus with each flow of the outer loop, the inner loop executes completely, which means if we have m flows for the outer loop and n number of flows for the outer loop, then this loop together will be executed m*n times.
For Example:
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
System.out.println(“LOOP DEMO”);
}
}
In the case of the nested loop given above:
Outer Loop
Counter variable = i
Condition – i<5
Increment/decrement – i++
Inner Loop
Counter variable = j
Condition – j<5
Increment/decrement – j++
Examples of Nested Loop in Java
Given below are the examples of Nested Loop in Java:
Example #1
Let’s write a program to print the below pattern:
*
**
***
****
*****
package Try;
class Demo
{
//static method
public static void main(String[] args)
{
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(i>=j) {
System.out.print('*');}
}
System.out.println("\n");
}
}
}
In the above program, 2 inner loops are used since the pattern that needs to be printed can be taken similar to a 2d array with ‘*’ as its element with 5 rows and 5 columns.
Also, if(i<=j) condition can be figured out using the locations of * present in the 2d array where counter for rows is I and for columns we use j.
I=1 | I=2 | I=3 | I=4 | I=5 | |
J=1 | * | ||||
J=2 | * | * | |||
J=3 | * | * | * | ||
J=4 | * | * | * | * | |
J=5 | * | * | * | * | * |
We can easily configure that we need to print * only when i<j.
Example #2
Let’s see the example to print a 2D matrix.
Code:
package Try;
class Demo
{
public static void printMatrix(int arr[][][]){
int i=0,j=0;
while(i<arr.length){
while(j<arr[i].length){
for (int k = 0; k <arr[j].length; k++)
System.out.println("arr[" + i + "][" + j + "]["+ k + "] = "+arr[i][j][k] );
j++;
}
i++;
j=0;
}
}
public static void main(String[] args)
{
int arr[][][] ={ { { 10, 2 }, { 30, 4 } }, { { 51, 6 }, { 79, 8 } } };
printMatrix(arr);
}
}
Output:
Explanation:
In the above program, we have used 3 loops to print the elements stored in a 3D Matrix using 3 counter variables. Thus, any number of loops can be tested as well as any type of loop can be used.
Conclusion
Nested loop refers to the placement of loop inside the loop to execute the operations that need multiple loop traversals such as printing star patterns or search operations on any collection data structure array or linked list. Although it helps to make our task easier, it also increases the complexity of the program thus must be used in an efficient manner.
Recommended Articles
This is a guide to the Nested Loop in Java. Here we discuss the introduction, examples, and how nested loop works in Java? respectively. You may also have a look at the following articles to learn more –