ADVERTISEMENT
ADVERTISEMENT

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

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

Problem Solution:

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 while and for loop to terminate the loop when the given if statement is true.

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.

Java Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.