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
// Nested for loop 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(); } } } |
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
// Naming the loop import java.io.*; class GFG { public static void main(String[] args) { // Type the name outside the loop outer: for ( int i = 0 ; i < 5 ; i++) { System.out.println( "GFG!" ); } } } |
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
// Break statements and naming the loops import java.lang.*; public class GFG { public static void main(String[] args) { // Using Label for outer and for loop outer: for ( int i = 1 ; i <= 3 ; i++) { // Using Label for inner and for loop inner: for ( int j = 1 ; j <= 3 ; j++) { if (j == 2 ) { break inner; } System.out.println(i + " " + j); } if (i == 2 ) { break outer; } } } } |
1 1 2 1