Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to break out of a while loop before the original condition is made false?

Is there a way to break out of a while loop before the original condition is made false?

for example if i have:

while (a==true) 
{ 
    doSomething() ; 
    if (d==false) get out of loop ;
    doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true() ;
} 

Is there any way of doing this?

like image 270
David Avatar asked Apr 15 '10 22:04

David


People also ask

How do you break out of a while loop early?

Breaking Out of While Loops. To break out of a while loop, you can use the endloop, continue, resume, or return statement.

Can you use break to get out of a while loop?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs.

Can you break out of a while loop Java?

Just use the break inside the "if" and it will break out of the "while". If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

Can you break out of a while loop Python?

Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.


4 Answers

Use the break statement.

if (!d) break;

Note that you don't need to compare with true or false in a boolean expression.

like image 174
BalusC Avatar answered Oct 23 '22 00:10

BalusC


break is the command you're looking for.

And don't compare to boolean constants - it really just obscures your meaning. Here's an alternate version:

while (a) 
{ 
    doSomething(); 
    if (!d)
        break;
    doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true();
} 
like image 20
Carl Manaster Avatar answered Oct 22 '22 23:10

Carl Manaster


Try this:

if(d==false) break;

This is called an "unlabeled" break statement, and its purpose is to terminate while, for, and do-while loops.

Reference here.

like image 43
Matthew Jones Avatar answered Oct 22 '22 22:10

Matthew Jones


break;

like image 33
Ben S Avatar answered Oct 22 '22 23:10

Ben S