C switch Statement

Switch case-control instruction

Switch-case is used when we have to make a choice between the number of alternatives for a given variable.

The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single

Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found.

If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.

Syntax,

Switch(integer-expression)

{

Case c1:

       Code;

Case c2:                                                         //c1,c2,c3 are constants

       Code;                                                       //Code is any valid C code

Case c3:

      Code;

default:

      Code;

}

The value of integer-expression is matched against c1,c2,c3……if it matched any of these cases, that case along with all subsequent “case” and “default” statements are executed.

Rules for switch statement in C language

1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all the cases will be executed present after the matched case. It is known as fall through the state of C switch statement.

Functioning of switch case statement

First, the integer expression specified in the switch statement is evaluated. This value is then matched one by one with the constant values given in the different cases. If a match is found, then all the statements specified in that case are executed along with the all the cases present after that case including the default statement. No two cases can have similar values. If the matched case contains a break statement, then all the cases present after that will be skipped, and the control comes out of the switch. Otherwise, all the cases following the matched case will be executed.

Let’s see a simple example of c language switch statement.

#include<stdio.h>
int main(){  
int number=0;   
printf("enter a number:");  
scanf("%d",&number);  
switch(number){  
case 10:  
printf("number is equals to 10");  
break;  
case 50:  
printf("number is equal to 50");  
break;  
case 100:  
printf("number is equal to 100");  
break;  
default:  
printf("number is not equal to 10, 50 or 100");  
}  
return 0;
}  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

Switch case example 2

Output

hi	

C Switch statement is fall-through

In C language, the switch statement is fall through; it means if you don’t use a break statement in the switch case, all the cases after the matching case will be executed.

Let’s try to understand the fall through state of switch statement by the example given below.

Output

enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

Output

enter a number:50
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100

Nested switch case statement

In C, we can have an inner switch embedded in an outer switch. Also, the case constants of the inner and outer switch may have common values and without any conflicts.

We considere the following program which the user to type his own ID, if the ID is valid it will ask him to enter his password, if the password is correct the program will print the name of the user, otherwise ,the program will print Incorrect Password and if the ID does not exist , the program will print Incorrect ID

#include <stdio.h>
int main() {
        int ID = 500;
        int password = 000;
        printf("Plese Enter Your ID:\n ");
        scanf("%d", & ID);
        switch (ID) {
            case 500:
                printf("Enter your password:\n ");
                scanf("%d", & password);
                switch (password) {
                    case 000:
                        printf("Welcome Dear Programmer\n");
                        break;
                    default:
                        printf("incorrect password");
                        break;
                }
                break;
            default:
                printf("incorrect ID");
                break;
        }
}

OUTPUT:

Plese Enter Your ID:
 500
Enter your password:
 000
Welcome Dear Programmer
  1. In the given program we have explained initialized two variables: ID and password
  2. An outer switch construct is used to compare the value entered in variable ID. It execute the block of statements associated with the matched case(when ID==500).
  3. If the block statement is executed with the matched case, an inner switch is used to compare the values entered in the variable password and execute the statements linked with the matched case(when password==000).
  4. Otherwise, the switch case will trigger the default case and print the appropriate text regarding the program outline.

Why do we need a Switch case?

There is one potential problem with the if-else statement which is the complexity of the program increases whenever the number of alternative path increases. If you use multiple if-else constructs in the program, a program might become difficult to read and comprehend. Sometimes it may even confuse the developer who himself wrote the program.

The solution to this problem is the switch statement.

Quick Quiz: Write a program to find the grade of a student given his marks based on below:

90-100A
80-90B
70-80C
60-70D
<70F

Important notes

  • We can use switch case statements even by writing in any order of our choice
  • Char values are allowed as they can be easily evaluated to an integer
  • A switch can occur within another, but in practice, this is rarely done

Practice Set

  1. What will be the output of this program?
int a=10;

if(a=11)
   printf(“I am 11”);
else
   printf(“I am not 11”);
  1. Write a program to find out whether a student is pass or fail; if it requires a total of 40% and at least 33% in each subject to pass. Assume 3 subjects and take marks as input from the user.
  2. Calculate income tax paid by an employee to the government as per the slabs mentioned below:
Income SlabTax
2.5L-5.0L5%
5.0L-10.0L20%
Above 10.0L30%

Note that there is no tax below 2.5L. Take income amount as an input from the user.

  1. Write a program to find whether a year entered by the user is a leap year or not. Take the year as input from the user.
  2. Write a program to determine whether a character entered by the user is lowercase or not.
  3. Write a program to find the greatest of four numbers entered by the user.

Was this article helpful?
YesNo

Leave a Comment

Your email address will not be published. Required fields are marked *