How to break any outer nested loop by referencing its name in java

Nested cycles are cycles within cycles, internal cycles within the body of external cycles.

Working:

  1. The first iteration of the outer cycle triggers the inner cycle, which executes fully.
  2. Then the second pass of the outer loop activates the inner loop again.
  3. This is repeated until the outer cycle is complete.
  4. Internal or external cycle interrupts will interrupt this process.

The Function of Nested loop :

 
// 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();
		}
	}
}

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

// 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!");
		}
	}
}

Output

GFG!
GFG!
GFG!
GFG!
GFG!

Rules to Label the loops:

  1. Cycle labels should be clear to avoid confusion.
  2. Use the label on the interrupt operator that is within range. (Below is the implementation)

 

// 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;
			}
		}
	}
}

Output

1 1
2 1

 

Submit Your Programming Assignment Details