Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer one.
Working:
- The first pass of the outer loop triggers the inner loop, which executes to completion.
- Then the second pass of the outer loop triggers the inner loop again.
- This repeats until the outer loop finishes.
- A break within either the inner or outer loop would interrupt this process.
The Function of Nested loop :
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
for ( int i = 0 ; i < 3 ; i++) {
for ( int j = 0 ; j < 3 ; j++) {
System.out.print( "GFG! " );
}
System.out.println();
}
}
}
|
Output
GFG! GFG! GFG!
GFG! GFG! GFG!
GFG! GFG! GFG!
Label the loops:
This is how we can label the name to the loop:
labelname :for(initialization;condition;incr/decr){
//code to be executed
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
outer:
for ( int i = 0 ; i < 5 ; i++) {
System.out.println( "GFG!" );
}
}
}
|
Output
GFG!
GFG!
GFG!
GFG!
GFG!
Rules to Label the loops:
- Label of the loop must be unique to avoid confusion.
- In the break statements use labels that are in scope. (Below is an implementation)
Java
import java.lang.*;
public class GFG {
public static void main(String[] args)
{
outer:
for ( int i = 1 ; i <= 3 ; i++) {
inner:
for ( int j = 1 ; j <= 3 ; j++) {
if (j == 2 ) {
break inner;
}
System.out.println(i + " " + j);
}
if (i == 2 ) {
break outer;
}
}
}
}
|
Last Updated :
21 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...