+ 5
How can I run multiple conditions in an while loop?
21 Answers
+ 20
by use of the logical operators
+ 17
Or even use the 'or' operator ( || ) ;P
while ( (x>42) || (y<42) || (n==42) ) {
/* ... */
}
+ 9
since a while loop only runs if its condition is true, you can connect multiple conditions with the Boolean and (&&)
while(condition1 && condition2 && condition3) {
// do something
}
+ 7
Even you can use both.
while(((5 > y) || (x < 5)) && (z != 10)) {
/* my statements... */
}
+ 7
You can use logical operators (&&, ||, !) or even the conditional operators (?:)
+ 7
It's pretty much been answered albeit without much explanation: || if you want either condition being true to keep it running, && if you want either condition being false to end it. I think you need an explanation, too...
With OR (||), we say loop if ANY of the following are true.
With AND (&&), we're saying EVERY one of these must be true.
I would like to add that if one condition or all conditions are false for && and || respectively, all code in your while block will not run. This could also be where you're going wrong (no code posted). If this is the case, a do-loop is better. Syntax:
do {
/* your code */
} while (condition) || (condition);
Hopefully this better clarifies things.
+ 5
Use or ||
+ 5
@Jamie, I agree with your solution but I myself made a lot of use in my past programming profession that included the CASE structure in it to execute the DO WHILE loop. To exit the WHILE LOOP, I used a simpel FOR ELSE condition to change the WHILE condition to exit the LOOP.
It is nice to see that some of you go the extra step to help a fellow programmer...
+ 3
And yet another method: You can combine if/case statements within your loop with the 'continue' command to add flow changes within a loop.
+ 2
Suppose in a while loop, you have two conditions, and any one needs to be true to proceed to the body, then in that case you can use the || operator between those two conditions, and in case you want both to be true, you can use && operator.
+ 1
By using if statements and logical operators such as &&, 11,!
+ 1
using && or ||
+ 1
using logical operators โ
+ 1
&& and ll
+ 1
link then using Boolean operators
0
use or function
while ( (a>10) || (b<10) || (m==10) )
{
/* have a fun */
}
0
You can use logical operators i.e. or,and,not to combine these conditions to get the required outputs.
0
Yes
- 1
while(condition)
{
while(condition)
{
while(condition)
{
}
}
}
- 1
f*********************************k