Search code examples
cdo-whileboolean-expression

Enforce input greater than or equal to 0 and less than 24


#include<stdio.h>

int main ()
{
int n,a=0,b=24;
do
  {
    scanf("%d",n); //ask the user to enter a value of n less than 24 
                  // but greater than 0. 
  } while(/*boolean expression logic*/)

if(a<n<b)
    {
    printf("%d\n",n);
    }
    return 0;
}

I need to evaluate:

If the value of n is greater than or equal to 0 and less than 24 (less than or equal to 23) then

.... go to the if statement and print the value of n

otherwise

... ask the user to input the value of n i.e. it should again go back in the loop.


Solution

  • You want the program to keep asking for values until n>=0 && n<24; in other words, you want to keep asking for values while !(n>=0 && n<24), which using De Morgan's law we can write as !(n>=0) || !(n<24), which can be reduced to n<0 || n>=24

    do
    {
        scanf("%d",n);
    }
    while(n<0 || n>=24)