C program to check whether a number is in a range of [min, max]

  • How to check whether a number is in the range of [min, max] using one comparison for both positive and negative numbers.

Algorithm to check whether a number belongs to range [min, max]
  • If a number N is in range of [min, max](i.e min<=N<=max), then (N-min) should be >= 0 and (N-max) should be <= 0.
  • Hence, if (N-min)*(N-max) <= 0 then N is in range of [min, max] otherwise out of range.
  • Above solution will work for positive as well as negative numbers.

C program to check whether a number is in given range.

#include<stdio.h>

int main() {
    int num, min, max;
    
    printf("Enter an integer\n");
    scanf("%d", &num);
    printf("Enter the minimum and maximum range\n");
    scanf("%d %d", &min, &max);
    
    if((num-min)*(num-max) <= 0){
        printf("%d is in range of [%d, %d]", num, min, max);
    } else {
     printf("%d is not in range of [%d, %d]", num, min, max);
    }

    return 0;
}
Output
Enter an integer
25
Enter the minimum and maximum range
10 40
25 is in range of [10, 40]
Enter an integer
50
Enter the minimum and maximum range
10 40
50 is not in range of [10, 40]