Home »
C programming language
Using range with switch case statement in C programming language
Learn: How we can use switch case with the case values in a range in C programming language? In this article, we are going to explain the same with an example.
Range of values with switch case statement in C
You can use a range of values with switch case statement; in this article we are going to discuss the same.
For example, if you want to execute same set of statements with a range of numbers, you do not need to write separate case values, you can use range like min_value ... max_value.
Example
If you want to check range from 1 to 10, you will have to write case 1 ... 10: there are spaces beween min_value, three dots (...) and max_value.
Consider the program:
#include <stdio.h>
int main()
{
int number;
//read number
printf("Enter any number (1-100): ");
scanf("%d",&number);
//switch case statement
switch(number)
{
//case values within a range
case 1 ... 50:
printf("Number is in between 1 to 50\n");
break;
//case values within a range
case 51 ... 100:
printf("Number is in between 51 to 100\n");
break;
//default case
default:
printf("Number is out of range!!!\n");
break;
}
return 0;
}
Output
First run:
Enter any number (1-100): 10
Number is in between 1 to 50
Second run:
Enter any number (1-100): 70
Number is in between 51 to 100
Third run:
Enter any number (1-100): 120
Number is out of range!!!
Example Explained
In first input, we entered 10 and it matches with case 1 ... 50 and the output is "Number is in between 1 to 50", same as in second input, we entered 70, which matches with case 51 ... 100 and the output is "Number is in between 51 to 100". And in this third input, we entered 120 which does not match with any case range, thus default case is executed and the output is "Number is out of range!!!".
By this way, we do not need to use write values with separate cases, if the values that you want to validate are in range and want to execute the same body (set of statements), we can use switch statement with the case values in a range.