Switch Case in C Programming: A Comprehensive Guide

Switch Case in C Programming: A Comprehensive Guide

7 mins read1.1K Views Comment
Updated on Feb 23, 2023 14:28 IST

In this article, we will learn about switch case in c programming, its syntax, flowchart and later in the article we will learn how does switch statement works with the help of examples.

2023_02_MicrosoftTeams-image-188.jpg

One can run a specific code among different available choices using a switch case statement. One may comprehend this function of c programming with an example of the menu at a restaurant; when a customer goes to a restaurant, there are several dishes offered by the restaurant that is mentioned in the menu, and then the customer chooses their cuisine among all alternatives. In this article, we will let you know all about switch cases in c programming.

Syntax of Switch Case

 
switch(expression)
{
case1: code1
break;
case2: code2
break;
case3: code3
break;
casen: coden
break;
default: code
break;
}
statement y;
Copy code

To get a picture of the switch case let’s proceed further to its flow chart.

Flowchart of Switch Statement

2023_02_image-78.jpg

This flowchart of the switch case describes the clear flow of the program.

Must Read: What is C Programming?

Must Read: C Programming Online Courses and Certifications

How Does the Switch Case Work?

First of all, the condition which is given in the switch keyword is entered, and then the program moves to the next step, where the case is checked if the case is checked the same as the value written in the switch, then the code associated with that specific case runs. And using the break keyword program moves directly to the codes below the switch statements and ends. 

Take into account that the expression which is taken by the switch must be an integer or a character value. 

To figure out the working process of the switch case, let’s proceed further to an example.

 
#include<stdio.h>
int main(){
int n=0; //initializing variable
printf("enter a number:");
scanf("%d",&n);
switch(n){ //number entered by user
case 1:
printf("number is equals to 1");
break; //break the execution of the switch statement if the case matches
case 2:
printf("number is equal to 2");
break;
case 3:
printf("number is equal to 3");
break;
//value of n doesn't match any case constants
default:
printf("number is not equal to 1, 2 or 3");
}
return 0;
}
Copy code

Output-

enter a number:5

number is not equal to 1, 2 or 3

Output-

enter a number:2

number is equal to 2

Explanation

As we know it by the syntax of switch case, there is an expression given with the switch keyword that is passed to the cases; if the value passed in the switch expression matches the case, then the code written in that specific case executes, and execution of switch statement stops by break keyword.

  • Here in the above example expression is entered by the user in switch case, i.e., 2, when it matches case 2.
  • The code of case 2 executes.
  • By using the break keyword, the execution of the switch statement stops and moves to the end of the program. 

Let’s push forward on different examples of switch cases to enhance one’s clear-headedness on the switch statement.

Program to create a calculator using a switch case

 
#include <stdio.h>
int main() {
char n; //declaring character variable
int a, b; //declaring integer variable a and b
printf("Enter an operator (/, -, *, +) ");
scanf("%c", &n);
printf("Enter two numbers ");
scanf("%d %d",&a, &b); //operands to be entered by user
switch(n) //value entered by user
{
case/:
printf("%d / %d = %d",a, b, a/b);
break;
case '+':
printf("%d + %d = %d",a, b, a+b);
break;
case '*':
printf("%d * %d = %d",a, b, a*b);
break;
case-:
printf("%d - %d = %d",a, b, a-b);
break;
//break the execution of the switch statement if the case matches
// value of n doesn’t match any case constant +, -, *, /
default:
printf("oops! wrong operator");
}
return 0;
}
Copy code

Output-

Enter an operator (/, -, *, +)  *

Enter two numbers 5 

8

5 * 8 = 40

Output-

Enter an operator (/, -, *, +): * 8 .

Enter two numbers 6

7

oops! wrong operator

Explanation

  • In the above instance, the value of the operator that is * is stored in the variable n and the value of both operands are stored in a and b correspondingly. When the value of n is entered as “*,” the program’s control jumps into the case’*’ and executes its code. 
  • In case of an invalid input entered by the user, the program’s control jumps into the default statement and runs its code. 

Program to choose any programming language using switch case

 
#include <stdio.h>
int main() {
char a; //declaring character variable
printf("Choose any category among (A, B, C, D): ");
scanf("%c", &a);
switch(a)
{
case 'A':
printf("You have selected python");
break;
case 'B':
printf("You have selected C++");
break;
case 'C':
printf("You have selected C");
break;
case 'D':
printf("You have selected Java");
break;
// value of a doesn't match any case constant that is A, B, C, D
default:
printf("oops! invalid choice");
}
return 0;
}
Copy code

Output-

Choose any category among (A, B, C, D): D

You have selected Java

Output-

Choose any category among (A, B, C, D): B

You have selected C++

Output-

Choose any category among (A, B, C, D): A

You have selected python

Output-

Choose any category among (A, B, C, D): 7

oops! invalid choice

Explanation-

It’s a simple program that prints the language name by selecting categories among A, B, C and D.

Use of break Keyword in Switch Case

The break keyword is used to end a particular block or case within the switch statement. In other words, the break keyword terminates the switch statement by ending the desired code block.
The use of the break keyword makes the switch case legible and apparent to the readers. If the break keyword would not be used after every case, then simply the control of the program will move to each case until the end of cases is achieved.
In order to prevent the execution of each case and to get the desired output, it is the bottom line to use a break after cases respectively.

Recommended online courses

Best-suited C / C++ courses for you

Learn C / C++ with these high-rated online courses

4.24 K
6 weeks
475
6 weeks
– / –
45 hours
4 K
80 hours
– / –
1 month
– / –
40 hours
– / –
2 months
– / –
1 year
4 K
80 hours

Nested Switch Statement in C Programming

Within a switch statement, one can write another switch statement that is called a nested switch statement.

Syntax of Nested Switch Case in C Programming:

 
Switch (exp1) {
case 1:
printf("external switch");
switch (exp2) {
case 1:
printf("internal Switch");
break;
case 2:
Statements;
break;
case 3:
statements;
break;
}
break;
case 2: //case2 of external switch
statements;
}
Copy code

Simple program to demonstrate the nested switch case in c programming.

 
#include<stdio.h>
int main() {
int x = 7; //initializing the value of x and y
int y = 9;
switch (x) { //outer switch
case 7:
printf("external switch\n");
switch (y) { //inner switch
case 9:
printf("Internal switch\n");
}
}
printf("Value of x = %d\n", x);
printf("Value of y =%d\n", y);
return 0;
}
Copy code

Output-

external switch

Internal switch

Value of x = 7

Value of y =9

Explanation 

In the above example, two switch statements are the inner and outer switch. The outer switch has case 7, and the inner switch has case 9. Arguments that are in the switch statement are already initialized at the beginning of the program. 

Program to demonstrate the use of nested switch case in c programming

 
#include<stdio.h>
int main()
{
int x,y;
printf("1.laptop\n");
printf("2.iphone\n");
printf("3.computer\n");
printf("choose one from the available options\n");
scanf("%d",&x); //value of x entered by the user
switch (x)
{
case 1:
//if a laptop is chosen;
printf("laptops are not available right now");
break;
case 2:
//if iPhone is chosen;
printf("iPhone 14\n");
printf("1.iPhone 14 pro\n");
printf("2.iPhone 14 pro max\n");
printf("choose one from the available options\n");
scanf("%d",&y);
break;
//internal switch to display the versions of the iPhone
//under the iPhone category
switch(y)
{
case 1:
// to be executed if y = 1;
printf("You chose iPhone 14 pro\n" );
break;
case 2:
// to be executed if y = 2;
printf("You chose iphone 14 pro max" );
break;
}
break;
}
}
Copy code

Output

1.laptop

2.iPhone

3. computer

choose one from the available options

2

iPhone 14

1. iPhone 14 pro

2.iPhone 14 pro max

choose one from the available options

2

You chose iPhone 14 pro max

Output

1. laptop

2. iPhone

3. computer

choose one from the available options

1

laptops are not available right now

Explanation –

  • In the above example, there are two switch cases first is the outer switch, and the other one is the inner switch. 
  • By using printf, a list is created that gives three options to the user that are laptop, iPhone, and computer. 
  • After entering 2 as an expression to the outer switch program jumps into case 2 where the user will find another list of available phones.
  • In case 2, when a user enters the value of y in the inner switch case as 2 then the program’s control will jump to case 2, and its code gets executed: “You chose iPhone 14 pro max”.
  • Using a nested switch case, one can choose any category from one item from the list of multiple items.

Conclusion

Concerning C language, the switch case can be considered the icing on the cake. In every case where we have to choose or select one option or category among all other available options is the best way of implementing switch cases in real-life problems. Even one can choose categories that come under other categories as well by nested switch case. A distinctive way of mastering the switch case is to implement more and more programs on the list and menus.

Contributed By: Srashti Soni

FAQs

What is a switch case in c programming?

Using a switch case statement one can run a specific code among different available choices.

What is the use of the break keyword in the switch case?

To end a particular block or case within the switch statement is done by using the break keyword.

What will happen if we don't use the break keyword in the switch case?

The control of the program will move to each case until the end of cases is achieved.

What type of expression a switch statement can take?

The expression which is taken by the switch must be an integer or a character value.

Can we implement a nested switch case in C programming?

Yes, Within a switch statement one can write another switch statement that is called a nested switch statement.

Where switch case is used in the real world?

Switch case can be used in every problem where we are choosing one option among all other categories.

How many cases we can write in switch case in c programming?

One can write any number of cases in a switch statement.

Which data type is not allowed in switch expression?

float, boolean, double, and long are not allowed in switch as arguments, on the other hand, integer or a character value is allowed.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio