Search code examples
ccomparison

How do I determine if a value is within a range?


I am relatively new to C, I have to do it for school unfortunately and I am having issues with it at the easiest exercises.

Here I have to check if a number is in a certain interval, for example between 4 and 6. I made it like this.

#include <stdio.h>

int main(){

  int i;

  printf("Value to check Interval \n");
  scanf("%s", i);
  if (i>4 && i<6){
    printf("%s Value is in first interval\n", i);
  }
}

The scanf to enter the number and check if it is in the interval. But even if I enter a number that is part of it, for example 5, the printf doesn't do anything. I tried also to add an else statement for numbers outside the interval, but also there the printf did not change anything.


Solution

  • It is because you have declared i variable as int and you are taking input as string so when it is checking condition it is getting null value in i variable and not able to enter if block check below code

        #include <stdio.h>
    
        int main(){
    
          int i;
            printf("Value to check Interval \n");
            scanf("%d",&i);
    
          if (i>4 && i<6){
            printf("%d Value is in first interval\n", i);
          }
        }
    

    try compiling your code without if condition i variable will return a null value