Home >Java >javaTutorial >Nested Loop in Java

Nested Loop in Java

WBOY
WBOYOriginal
2024-08-30 15:25:34526browse

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.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

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

Nested Loop in Java

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:

  1. Initialization: This step refers to initializing the value of the counter.
  2. Condition: This condition refers to the comparison that needs to be true for continuing the execution of the loop.
  3. 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.

Note: There are no limitations on the number of loops that can be nested as well as the type of loops that can be nested, one can use any type of loop, but one must take care as it affects the time complexity of the program and thus affects the performance.

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:

*

**

***

****

*****

Code:
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.<em>out</em>.print('*');}
}
System.<em>out</em>.println("\n");
}
}
}
Output: Nested Loop in Java Explanation:

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

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:

Nested Loop in Java

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.

The above is the detailed content of Nested Loop in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:For-Each loop in JavaNext article:For-Each loop in Java