Search code examples
csyntaxdo-whileprompt

Why is my program getting stuck in my do while loop?


enter image description here enter image description here

My program seems to be getting stuck in the do while loop. I want it to re-prompt the user if they enter a digit that is not zero or one


Solution

  • What if x == 0? x != 1 will be true, and the whole condition will be true.

    What if x == 1? x != 0 will be true, and the whole condition will be true.

    What if x == 2? x != 0 will be true, and the whole condition will be true.

    So, no matter what, your condition will be true, and you will continue looping.


    You want the following to be true:

    (x == 0 || x == 1) && (y == 0 || y == 1)
    

    So you want to loop while it's false.

    do { } while (!((x == 0 || x == 1) && (y == 0 || y == 1)));
    

    !(P && Q) is equivalent to !P || !Q, and
    !(P || Q) is equivalent to !P && !Q

    This means the following are equivalent to the above:

    do { } while (!(x == 0 || x == 1) || !(y == 0 || y == 1));
    
    do { } while ((x != 0 && x != 1) || (y != 0 && y != 1));