Switch Case Using Range in C



In C, a switch case is a control flow statement used to compare a variable with specific values and execute different blocks of code depending on which value matches. For example

switch(num) {
   case 1: printf("One"); break;
   case 2: printf("Two"); break;
   default: printf("Other");
}

Here, the switch case checks exact matches only. But sometimes, we want to check if a value falls within a range, like 1-5 or 'A'-'Z'. Instead of writing a separate case for each value, we can define a range of values in a single case. This is called a switch case with ranges. For exmaple −

switch(num) {
   case 1 ... 5: printf("Between 1 and 5"); break;
   case 6 ... 10: printf("Between 6 and 10"); break;
   default: printf("Other");
}

Switch Case Using Range

A switch case using ranges handles multiple consecutive values in one case. Instead of writing a separate case for each number or character, we define a range and the same block of statements runs for all values in that range.

We cannot use ranges in standard C, but the GNU C compiler provides this feature as a case range extension.

Syntax for Switch Case Using Range

Following is the syntax for using ranges in a switch case statement.

switch (value) {
   case lower_range ... higher_range:
      // code block
      break;
   default:
      // code block
}

Here, lower_range is the starting value and higher_range is the ending value. We must put spaces around the ellipsis (...) to make a valid syntax.

Steps to Implement Range Handling

To implement switch case with range handling, we first group the variable into categories and then use the switch to check which category it belongs to. Here's how we handle ranges-

  • First, we use if statements to check which range the value belongs to, like 1-10, 11-20, or 21-30.
  • Then, we assign each range a number, such as 1, 2, or 3, to represent it.
  • Next, pass this number to the switch case where each case corresponds to one range.
  • The switch case checks the number and runs the code for that range.
  • Finally, we add a default case to handle values outside the defined ranges.

Example: Simple Range Check

Let's see a simple example where we will use two ranges inside the switch case and check if a number belongs to the range 1-5 or 6-10. If it does not belong to any of these ranges, then the default statement will get printed.

#include <stdio.h>

int main() {
   int number = 7;  // You can change the value to test different cases

   switch (number) {
      case 1 ... 5:
         printf("The number is between 1 and 5.\n");
         break;
      case 6 ... 10:
         printf("The number is between 6 and 10.\n");
         break;
      default:
         printf("The number is outside the range 1 to 10.\n");
   }
   return 0;
}

Following is the output of the above program −

The number is between 6 and 10.

Example: Using if-else for Ranges with Switch Case

In this example, we check which range a number belongs to and display a message. We first use if-else statements to assign the number to a range such as 1-10, 11-20, 21-30, or out of range, and then the switch case prints the message corresponding to that range.

#include <stdio.h>

int main() {
   int number = 17;  // Set the number directly

   // Normalize the number into a range
   int range;
   if (number >= 1 && number <= 10) {
      range = 1;  // Range 1-10
   } else if (number >= 11 && number <= 20) {
      range = 2;  // Range 11-20
   } else if (number >= 21 && number <= 30) {
      range = 3;  // Range 21-30
   } else {
      range = 4;  // Out of range
   }

   // Use switch to handle the different ranges
   switch(range) {
      case 1:
         printf("The number is between 1 and 10\n");
         break;
      case 2:
         printf("The number is between 11 and 20\n");
         break;
      case 3:
         printf("The number is between 21 and 30\n");
         break;
      default:
         printf("The number is out of range\n");
   }
   return 0;
}

Following is the output of the above program, showing which range the given number belongs to.

The number is between 11 and 20

Example: Handling Character Ranges in Switch Case

In this example, we check what type of character a variable contains. The switch case checks whether the character is a lowercase letter, an uppercase letter, or a digit, and prints the corresponding message. Any character outside these ranges is handled by the default case.

#include <stdio.h>

int main() {
   char ch = 'G';  // Set the character directly

   // Switch-case with ranges
   switch (ch) {
      case 'a' ... 'z':  // Lowercase letters range
         printf("%c is a lowercase alphabet\n", ch);
         break;
      case 'A' ... 'Z':  // Uppercase letters range
         printf("%c is an uppercase alphabet\n", ch);
         break;
      case '0' ... '9':  // Digits range
         printf("%c is a digit\n", ch);
         break;
      default:
         printf("%c is a non-alphanumeric character\n", ch);
   }
   return 0;
}

Below is the output of the above program where it shows the type of the given character.

G is an uppercase alphabet

Example: Using Category Mapping with Switch Case

In this example, we group marks into categories by dividing them by 10. For example, marks from 90 to 100 fall into category 9 or 10, marks from 80 to 89 fall into category 8, and so on. Then, the switch case prints the message for that category.

#include <stdio.h>

int main() {
   int marks = 87;  // Set the marks directly

   // Convert marks into categories (divide by 10)
   int category = marks / 10;

   // Handle ranges using switch
   switch(category) {
      case 10:   // For 100
      case 9:    // For 90-99
         printf("Excellent! Grade A\n");
         break;
      case 8:    // For 80-89
         printf("Very Good! Grade B\n");
         break;
      case 7:    // For 70-79
         printf("Good! Grade C\n");
         break;
      case 6:    // For 60-69
         printf("Satisfactory! Grade D\n");
         break;
      default:   // For below 60
         printf("Needs Improvement! Grade F\n");
   }
   return 0;
}

Below is the output of the program, which divides the given marks and shows their category.

Very Good! Grade B

Errors in Switch Case Using Ranges

When using ranges in switch case, there are a few important things to keep in mind −

Invalid Range (low > high): If the low value is greater than the high value, the compiler will give an error.

Example of incorrect range −

case 5 ... 1:  // This will cause an error

Overlapping Ranges: If you try to define multiple case ranges that overlap, the compiler will give an error.

Example of incorrect overlapping ranges −

case 1 ... 5:
case 3 ... 7:  // Overlap error

In this chapter, we learned how to use ranges with switch cases to handle multiple consecutive values together. We covered this for both numbers and characters, and also looked at situations where errors can occur.

Advertisements