Programming Noob Programming Noob - 1 month ago 6
C Question

How to write a while loop with multiple conditions in C

Hey so 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 kinda tried:

#include <stdio.h>

int main () {
int Num;

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

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

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


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

Answer

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