Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+8 votes
asked in CSC211_Winter2018 by (1 point)

1 Answer

+5 votes

At times it is easier to think about when you want an indefinite loop to stop rather than when you want it to continue. For example, I want the loop to stop when the variable x is greater than 5 and less than 20. As a Java boolean expression, x > 5 && x < 20 would be true for a number like 7.

For a while loop, however, you need the boolean expression evaluating to true when the loop should continue, not stop. The boolean expression to continue would be the negation of the boolean expression to stop. The negation of x > 5 && x < 20 is !(x > 5 && x < 20) or equivalently using DeMorgan's Law x <= 5 || x >= 20. I would prefer the second version if I were coding the while loop.

while (x <= 5 || x >= 20){........

answered by (1 point)
...