C - Switch with multiple case numbers
If the ranges are consistent, then you can throw away some of the data:
switch (x / 10 )
{
case 0:
case 1:
case 2: // x is 0 - 29
break ;
// etc ...
}
Otherwise you'll have to do a little bit of hackery around the edges.
With GCC and Clang, you can use case ranges, like this:
switch (x){
case 1 ... 30:
printf ("The number you entered is >= 1 and <= 30\n");
break;
}
The only cross-compiler solution is to use case statements like this:
switch (x){
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
printf ("The number you entered is >= 1 and <= 6\n");
break;
}
Edit: Using something to the effect of switch (x / 10)
is another good way of doing this. It may be simpler to use GCC case ranges when the ranges aren't differences of 10
, but on the other hand your professor might not take a GCC extension as an answer.
Try this ...
#include <stdio.h>
main()
{
int x;
char ch1;
printf("Enter a number: ");
scanf("%d",&x);
int y=ceil(x/30.0);
switch(y)
{
case 1:
printf("The number you entered is >= 1 and <= 30");
printf("\nTake Briefcase Number 1");
break;
case 2:
printf("The number you entered is >= 31 and <= 60");
printf("\nTake Briefcase Number 2");
break;
case 3:
printf("The number you entered is >= 61 and <= 90");
printf("\nTake Briefcase Number 3");
break;
case 4:
printf("The number you entered is >= 91 and <= 100");
printf("\nTake Briefcase Number 4");
break;
default:
printf("Not in the number range");
break;
}
getch();
}