The Wayback Machine - https://web.archive.org/web/20241005022647/https://www.geeksforgeeks.org/using-range-switch-case-cc/
Open In App

Using Range in switch Case in C

Last Updated : 26 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

You all are familiar with switch case in C, but did you know you can use a range of numbers instead of a single number or character in the case statement? Range in switch case can be useful when we want to run the same set of statements for a range of numbers so that we do not have to write cases separately for each value.

  • That is the case range extension of the GNU C compiler and not standard C.
  • You can specify a range of consecutive values in a single case label.

Syntax

The syntax for using range case is:

case low ... high:

It can be used for a range of ASCII character codes like this:

case 'A' ... 'Z':

You need to Write spaces around the ellipses ( … ). For example, write this:

// Correct  -   case 1 ... 5: 
// Wrong -    case 1...5: 

The below program illustrates the use of range in switch case.

C




// C program to illustrate
// using range in switch case
#include <stdio.h>
int main()
{
    int arr[] = { 1, 5, 15, 20 };
 
    for (int i = 0; i < 4; i++) {
        switch (arr[i]) {
            // range 1 to 6
        case 1 ... 6:
            printf("%d in range 1 to 6\n", arr[i]);
            break;
            // range 19 to 20
        case 19 ... 20:
            printf("%d in range 19 to 20\n", arr[i]);
            break;
        default:
            printf("%d not in range\n", arr[i]);
            break;
        }
    }
    return 0;
}


Output

1 in range 1 to 6
5 in range 1 to 6
15 not in range
20 in range 19 to 20

Complexity Analysis

  • Time Complexity: O(n), where n is the size of array arr.
  • Auxiliary Space: O(1)

Error conditions

  1. low > high: The compiler gives an error message.
  2. Overlapping case values: If the value of a case label is within a case range that has already been used in the switch statement, the compiler gives an error message.

Exercise

  • You can try the above program for a char array by modifying the char array and case statement.


Previous Article
Next Article

Similar Reads

Using Range in C++ Switch Case
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 RangeUsing ran
2 min read
Data type of case labels of switch statement in C++?
In C++ switch statement, the expression of each case label must be an integer constant expression. For example, the following program fails in compilation. C/C++ Code /* Using non-const in case label */ #include<stdio.h> int main() { int i = 10; int c = 10; switch(c) { case i: // not a "const int" expression printf("Value of c
2 min read
Output of C programs | Set 30 (Switch Case)
Prerequisite - Switch Case in C/C++ Interesting Problems of Switch statement in C/C++ Program 1 #include <stdio.h> int main() { int num = 2; switch (num + 2) { case 1: printf("Case 1: "); case 2: printf("Case 2: "); case 3: printf("Case 3: "); default: printf("Default: "); } return 0; } Output: Default:
2 min read
Print individual digits as words without using if or switch
Given a number, print words for individual digits. It is not allowed to use if or switch.Examples: Input: n = 123 Output: One Two Three Input: n = 350 Output: Three Five Zero We strongly recommend you to minimize your browser and try this yourself first. The idea is to use an array of strings to store digit to word mappings. Below are steps.Let the
5 min read
C++17 new feature : If Else and Switch Statements with initializers
In many cases, we need to check the value of something returned by a function and perform conditional operations based on this value. So our code looks something like this // Some function return_type foo(params) // Call function with params and // store return in var auto var = foo(params); if (var == /* some value */) { //Do Something } else { //
3 min read
Interesting facts about switch statement in C
Prerequisite - Switch Statement in C Switch is a control statement that allows a value to change control of execution. C/C++ Code // Following is a simple program to demonstrate syntax of switch. #include &lt;stdio.h&gt; int main() { int x = 2; switch (x) { case 1: printf(&quot;Choice is 1&quot;); break; case 2: printf(&quot;Cho
3 min read
Difference Between if-else and switch in C
In C programming both switch statements and if-else statements are used to perform decision-making and control the flow of the program according to predefined conditions. In this article, we will discuss the differences between the if-else and switch statements. switch StatementA control flow statement called a switch statement enables a program to
4 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
Switch Statement in C++
The C++ Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. It is an alternative to the long if-else-if ladder which provides an easy way to dispatch execution to different parts of code based on the value of the expression. What is a switc
9 min read
Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
Given three integers a, b and c. You need to select one integer from the range [a, b] and one integer from the range [b, c] and add them. The task to calculate the number of ways to obtain the sum for all the numbers in the range [1, b+c]. Examples: Input: a = 1, b = 2, c = 2 Output: 0, 0, 1, 1 Explanation: The numbers to be obtained are [1, b+c] =
10 min read
Test Case Generation | Set 6 (Random Unweighted Binary Tree)
Generating Random Unweighted Binary Tree: Since this is a tree, the test data generation plan is such that no cycle gets formed.The number of edges is one less than the number of vertices.For each RUN, first print the count of nodes say, N and the next N - 1 lines are of the form (a, b) where a is the parent of b.Each node contains at most 2 childr
10 min read
How to delete a range of values from the List using Iterator
Given a List, the task is to delete a range of values from this List using Iterator. Example: Input: list = [10 20 30 40 50 60 70 80 90], start_iterator = 3, end_iterator = 8 Output: 10 20 80 90 Input: list = [1 2 3 4 5] start_iterator = 1, end_iterator = 3 Output: 3 4 5 Approach: In this method, a range of elements are deleted from the list. This
2 min read
Erase Range of Elements From List Using Iterators in C++ STL
Prerequisites:List in C++Iterators in C++ A list is a type of container which requires the same properties as a doubly linked list. We can insert elements from either side of the list, but accessing elements with an index is not possible in the list. So, removing elements from the list is not an easy task. But, we have a method to remove multiple e
2 min read
How to check whether a number is in the range[low, high] using one comparison ?
This is simple, but interesting programming puzzle. Given three integers, low, high and x such that high >= low. How to check if x lies in range [low, high] or not using single comparison. For example, if range is [10, 100] and number is 30, then output is true and if the number is 5, then output is false for same range. A simple solution is com
3 min read
Distribution of a Number in Array within a Range
Given the integers S, N, K, L, and R where S has to be distributed in an array of size N such that each element must be from the range [L, R] and the sum of K elements of the array should be greater than the sum of the remaining N - K elements whose sum is equal to Sk and these elements are in non-increasing order. Examples: Input: N = 5, K = 3, L
9 min read
Queries for Nth smallest character for a given range in a string
Given a string str which consists of only lowercase letters and an array arr[][] that represents range queries on the given string str where each query contains 3 integers, {L, R, N} such that for each query we have to output the Nth smallest character in the given range [L, R] as specified in the query. Examples: Input: str = "afbccdeb", arr[][] =
14 min read
Different types of range-based for loop iterators in C++
Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container). This is very efficient when used with the standard library container (as will be used in this article) as there will be no wrong access to memory outside the scope of the iterable. The loop will automatically star
5 min read
Count Full Prime numbers in a given range
Given two integers L and R, the task is to count the number of full prime numbers that are present in the given range. A number is said to be Full prime if the number itself is prime and all its digits are also prime. Examples: 53 is Full Prime because it is prime and all its digits (5 and 3) are also prime.13 is not Full Prime because it has a non
8 min read
Minimum product modulo N possible for any pair from a given range
Given three integers L, R, and N, the task is to find the minimum possible value of (i * j) % N, where L ? i < j ? R. Examples: Input: L = 2020, R = 2040, N = 2019Output: 2Explanation: (2020 * 2021) % 2019 = 2 Input: L = 15, R = 30, N = 15Output: 0Explanation: If one of the elements of the pair is 15, then the product of all such pairs will be d
5 min read
Reverse given range of String for M queries
Given a string S of length N and an array of queries A[] of size M, the task is to find the final string after performing M operations on the string. In each operation reverse a segment of the string S from position (A[i] to N-A[i]+1). Examples: Input: N = 6, S = "abcdef", M = 3, A = {1, 2, 3}Output: "fbdcea"Explanation: After the first operation,
15 min read
How to Insert a Range of Elements in a Set in C++ STL?
Prerequisites: Set in C++ Sets in C++ are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. Syntax: set<datatype> set_name; Some Basic Functions Associated with Set: begin(): Returns an ite
2 min read
Count of divisors of product of an Array in range L to R for Q queries
Given an array arr of size N and Q queries of the form [L, R], the task is to find the number of divisors of the product of this array in the given range.Note: The ranges are 1-positioned.Constraints: 1<= N, Q <= 105, 1<= arr[i] <= 106. Examples: Input: arr[] = {4, 1, 9, 12, 5, 3}, Q = {{1, 3}, {3, 5}} Output: 9 24 Input: arr[] = {5, 2,
15+ min read
How to print range of basic data types without any library function and constant in C?
How to write C code to print range of basic data types like int, char, short int, unsigned int, unsigned char etc? It is assumed that signed numbers are stored in 2's complement form. We strongly recommend to minimize the browser and try this yourself first. Following are the steps to be followed for unsigned data types. 1) Find number of bytes for
4 min read
What Happen When We Exceed Valid Range of Built-in Data Types in C++?
In this article, we will look at what happened when we exceed the valid range of built-in data types in C++ with some examples.Example 1: Program to show what happens when we cross the range of 'char'.Here, a is declared as char. Here the loop is working from 0 to 225. So, it should print from 0 to 225, then stop. But it will generate an infinite l
4 min read
Range-based for loop in C++
Range-based for loop in C++ has been added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container. for ( range_declaration : range_expression ) loop_statementParameters :range_declaration : a declaration of a named variab
3 min read
Count number of unique Triangles using STL | Set 1 (Using set)
We are given n triangles along with length of their three sides as a,b,c. Now we need to count number of unique triangles out of these n given triangles. Two triangles are different from one another if they have at least one of the sides different.Example: Input: arr[] = {{1, 2, 2}, {4, 5, 6}, {4, 5, 6} Output: 2 Input: arr[] = {{4, 5, 6}, {6, 5, 4
3 min read
Print pattern using only one loop | Set 1 (Using setw)
Print simple patterns like below using single line of code under loop. Examples: Input : 5Output : * ** *** *********Input : 6Output : * ** *** **** ***********setw(n) Creates n columns and fills these n columns from right. We fill i of them with a given character, here we create a string with i asterisks using string constructor. setfill() Used to
4 min read
How to print % using printf()?
Here is the standard prototype of printf function in C: int printf(const char *format, ...); The format string is composed of zero or more directives: ordinary characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of argument (and it is an error if insufficiently many arguments are given). The char
1 min read
Print "Even" or "Odd" without using conditional statement
Write a program that accepts a number from the user and prints "Even" if the entered number is even and prints "Odd" if the number is odd. You are not allowed to use any comparison (==, <,>,...etc) or conditional statements (if, else, switch, ternary operator,. Etc). Method 1 Below is a tricky code can be used to print "Even" or "Odd" accordi
4 min read
C++ Inline Namespaces and Usage of the "using" Directive Inside Namespaces
Prerequisite: Namespaces in C++ In C++, namespaces can be nested, and the resolution of namespace variables is hierarchical. An inline namespace is a namespace that uses the optional keyword inline in its original-namespace definition. This allows the identifiers of the nested inline namespace to behave as if they are the identifier of the parent/e
3 min read
Practice Tags :