×

Java Programs

Java Practice

Java program to demonstrate the break statement with a nested loop

Here, we are demonstrating the use of break statement with a nested loop.
Submitted by Nidhi, on March 09, 2022

Problem statement

The break statement in Java terminates the loop immediately, and the control of the program moves to the next statement written after the loop body.

In this program, we will use the break statement with the nested while loop. If we use the break statement inside the inner loop then it terminates the only inner loop.

Java program to demonstrate the break statement with a nested loop

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.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.