Nested cycles are cycles within cycles, internal cycles within the body of external cycles.
Working:
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:
// 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
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.