# Thread: Check if a value is in a particular range.

1. ## Check if a value is in a particular range.

Hi,

I want to test if the value in a variable is in a particular range. And i used the following program to test if what i'm thinkin is correct. However, when i ran that program, the statements execute even if the number is not in the range. I think it's the evaluation part which i've done wrong. Pls tell me the correct way thnx in advance!

Code:
```#include <stdio.h>

int main()
{
int i = 5;

if ( (1 <= i <= 5) )
printf( "1 to 5\n" );

if ( 6 <= i <= 7 )
printf( "6 to 7\n" );

if ( 8 <= i <= 10 )
printf( "8 to 10\n" );

getch();
return 0;
}``` 2. just need to use && (AND)

Code:
```#include <stdio.h>
#include <conio.h> // and you need conio for getch() i think

int main()
{
int i = 5;

if ( i >= 1 && i <= 5 )
printf( "1 to 5\n" );

if ( i >= 6 && i <= 7 )
printf( "6 to 7\n" );

if ( i >= 8 && i <= 10 )
printf( "8 to 10\n" );

getch();
return 0;
}``` 3. thought of that, but is it the ONLY way ?

if it is just don't reply. THnx a lot Brian. 4. well you could do
Code:
```if(i <= 1)
{
if(i >= 3)
{
printf("From 1-to-3");
}
}``` 5. Or

Code:
```if (a < 3)
{
..
}
else if (a < 6)
{
..
}
else if (...)
...``` 6. Yeah, what shiro said. 7. you could always use a switch

#include <stdio.h>
#include <conio.h> // and you need conio for getch() i think

int main()
{
int j, i = 5;

printf("Enter number to test >");
scanf("%d", j);

switch(j)
{
case 1 :
case 2 :
case 3 :
case 4 :
case 5 : printf( "1 to 5\n" );
break;
case 6 :
case 7 : printf( "6 to 7\n" );
break;
case 8 :
case 9 :
case10 : printf( "8 to 10\n" );
break;
default :;

getch();/*i don't undersatnd what this is for */
return 0;
} Popular pages Recent additions 