The source code to demonstrate the break statement with the nested loop is given below. The given program is compiled and executed successfully.
// Java program to demonstrate the break statement
// with a nested loop
public class Main {
public static void main(String[] args) {
int cnt1 = 1;
int cnt2 = 0;
while (cnt1 <= 5) {
cnt2 = 1;
while (cnt2 <= 10) {
System.out.print(cnt1 + " ");
if (cnt2 == 5) {
break;
}
cnt2 = cnt2 + 1;
}
cnt1 = cnt1 + 1;
System.out.println();
}
}
}
Output:
1 2 3 4 5
1 2 3 4 5
Explanation:
In the above program, we created a public class Main. It contains a static method main().
The main() method is an entry point for the program. Here, we used the break statement inside the inner loop. In the case of a nested loop, if we use the break statement nested loop inside the inner loop then it terminates the inner loop.
In our program, the normally inner loop executes 10 times but it will execute only 5 times because of the break statement.
Program/Source Code:
The source code to demonstrate the break statement with the nested loop is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created a public class Main. It contains a static method main().
The main() method is an entry point for the program. Here, we used the break statement inside the inner loop. In the case of a nested loop, if we use the break statement nested loop inside the inner loop then it terminates the inner loop.
In our program, the normally inner loop executes 10 times but it will execute only 5 times because of the break statement.
need an explanation for this answer? contact us directly to get an explanation for this answer