Open In App

Using Range in C++ Switch Case

Last Updated : 10 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, we generally know about the switch case which means we give an attribute to the switch case and write down the cases in it so that for each case value we can make desired statements to get executed. We can also define the cases with a range of values instead of a single value.

Prerequisites: Switch Case in C++

Switch Case with Range

Using range in switch case means in the above scenario we used to check only one value to the given attribute but now we can check a range of values to the given attribute in a single case

So for using a range in the switch case let’s refer to an example

switch(a){
case '1': .....#some statements to execute
case '2': ....#some another set of statements to execute.
}

In this case a is checked to 1 and 2 only know if we want to check it for numbers 1 to 100 and we have to print desired statements for them then we have to write 100 cases to check it .So its very long and instead we can use range in case as syntax mentioned below.

Syntax

case 'low' .. 'high':
#set of statements to execute( low<high )

Example with range in Switch Case

switch(a){ case 1 … 100 : // Statements case 101 … 200: // Statements}

Example of Using Range in C++ Switch Case

Below is the implementation of the above topic:

C++




// C++ Program to implement
// Using Range in Swtich Case
#include<iostream>
using namespace std;
  
// main function
int main()
{
    int a=8;
  
      // Switch Case
    switch(a)
    {
        // Range added to Switch case
        case 4 ... 10:
            cout<<"a is range 4 to 10"<<endl;
            break;
    }
}


Output :

a is range 4 to 10

Note:

  1. We have to exactly use 3 dots other wise it will give us error while compilation.
  2. If low>high then also we will get an error

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads