Search code examples
cwhile-loopconditional-statementslogical-operatorslogical-and

How to write a while loop with multiple conditions in C


I tried doing a while loop with multiple conditions, but I just can't figure out how to make it work. I've made a short example of what I kind of tried:

#include <stdio.h>

int main () {
    int Num;

    printf("Please enter an odd integer between 5-20: ");
    scanf("%d", &Num);

    while ((Num % 2 == 0) && (5 > Num) && (20 < Num)) {

        printf("Not a valid input!");
        printf("Please enter an odd integer between 5-20: ");
        scanf("%d", &Num);
    }
}

I believe I'm using the correct logical operator, right?


Solution

  • Nope, you're wrong. Think of the logic

    (5>Num) && (20<Num)
    

    Num cannot be <5 and >20 at the same time. You either

    • need the logical OR operator
    • Change the range to something like (Num > 5) && (Num < 20) or something