Reputation: 81
while( first1<=last1 || first2<=last2 )
while( first1<=last1 && first2<=last2 )
I am just trying to make sure I am correct. For an "or" condition it means that it only needs one of those to be true to enter the while loop, while the "and" condition needs both to be true to enter the while loop? First time I've seen the "and" and "or" operation not in an if statement, so i am a little confused.
Upvotes: 0
Views: 412
Reputation: 3674
They work exactly the same as in an if statement, the location does not matter.
Here are some truth tables to clarify.
a b a OR b a AND b
false false | false | false
false true | true | false
true false | true | false
true true | true | true
Upvotes: 0
Reputation: 392
This is a classic example of java short circuiting.
int x = 14;
while(x>10 && x<50)
In this statement the first part is true but for an and statement both operands must be true for it to excecute. Now it looks at the next side that is true asweell so the while loop will excecute. If x had been -11 then the first part would be false and it would not even look at the other side becasue the statement is already false. The same is with or ( || ) . Or will short circuit when the left hand side is true then it doesnt even look at the other side.
Upvotes: 0
Reputation: 11867
Yep! && and || work exactly as they do in an if statement. In fact, you can interpret the condition of a while loop as an if statement -- if
the condition is true, enter the loop
Upvotes: 3