I used these condition in do while loop , and I still getting the forever loop. It just doesn't stop.

while( x > 0 || x < 23);

3 Answers 3


Your condition is flawed. If x is greater than 0 OR x is less than 23, the loop will keep going. x > 0 includes all positive numbers, and x < 23 includes all negative numbers in addition to positive numbers up to 23. There are no integer values for which both would not be true, and thus you will forever be in that loop. Remember, || (OR) means if either of them are true, the entire thing is true. Simply switching to && will not fix the problem, however. You want your loop condition to be the opposite of the condition you are looking for, so that as long as your desired condition is NOT met, you stay inside the loop.


To get out of a loop, you need two thing

  1. the loop continuation condition
  2. an update to the value that's involved in that condition

Meanwhile, in case x > 0 or < 23 and it doesn't change, the loop will keep executing infinitely.


Your condition remains true for all test cases. Eg, if you input -10,

while( x > 0 || x < 23)

will evaluate to true since x < 23 is true.

If you input 35,

while( x > 0 || x < 23)

will evaluate to true since x > 0 is true. Hence, this is an infinite loop.

If you wish to run a piece of code for an input between the two numbers, use

while(x > 0 && x < 23)
  • This would keep asking for input as long as x is between 1-22 inclusive, and it would stop if x is less than 1 or greater than 23.
    – m_duran
    Jul 18, 2014 at 4:09
  • This is what he wants right?
    – kray
    Jul 18, 2014 at 4:20
  • No, it is backwards. 1-23 is what you are looking for as an input, so once that number is input, you want to exit the loop. You want to stay inside the loop as long as the input is NOT in that range to keep asking for proper input.
    – m_duran
    Jul 18, 2014 at 4:28
  • Right. No this condition was for what he asked in the question. Maybe he's trying something else? Since he said he wants to run the loop for a number between 0 and 23 I wrote this condition.
    – kray
    Jul 18, 2014 at 6:05
  • This is for pset1, this loop is to make sure that the input is between 1 and 23 inclusive. As long as the input is not in this range, you want to stay in the loop to ask for input again.
    – m_duran
    Jul 18, 2014 at 19:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .