Q:

Java program to demonstrate the break statement with while and for loop

belongs to collection: Java Basic Programs

0

Java program to demonstrate the break statement with while and for loop

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the break statement with the while and for loop is given below. The given program is compiled and executed successfully.

// Java program to demonstrate the break statement 
// with "while" and "for" loop

public class Main {
  public static void main(String[] args) {
    int cnt = 1;

    while (cnt <= 10) {
      System.out.print(cnt + " ");
      if (cnt == 5) {
        break;
      }
      cnt = cnt + 1;
    }

    System.out.println();

    for (cnt = 1; cnt <= 10; cnt++) {
      System.out.print(cnt + " ");
      if (cnt == 5) {
        break;
      }
    }
  }
}

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 with while and for loop to terminate the loop when the value of the cnt variable is equal to 5.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to demonstrate the break statement wi... >>
<< Java program to implement nested loop using for lo...