All About Switch Statement in C++

All About Switch Statement in C++

3 mins read1.3K Views Comment
Updated on Aug 27, 2024 13:32 IST

A switch statement in C++ allows variables to be tested for equality against set of values called case. It evaluates a given expression and executes statements associated with it based on the evaluated value.

2022_08_All-About-While-and-Do…-While-Loop-in-C-1.jpg

In this article, we will learn how decision-making is performed in C++ by using a switch statement. The switch case statements follow a selection-control mechanism and allow a value to alter control of execution. Today, let’s understand the logic behind them in detail.

We will be covering the following sections:

What is Switch Statement in C++?

The switch case statement in C++ evaluates a given expression and executes the block of code associated with it if the expression holds true. Similar to the if…else statement in C++, the switch case statements offer an easy way to relay the execution control to different parts of code based on the value of the expression (condition).

Switch Statement Syntax

Here’s the syntax for the switch statement in C++:


 
switch (test expression) {
case value1:
// if expression = value1;
// execute this block of code
break;
case value2:
// if expression = value2;
// execute this block of code
break;
.
.
.
default:
// execute default code if
// no condition is satisfied
}
Copy code

The test expression, or condition, is evaluated by the switch statement and compared with the values of each case label.

The block of code corresponding to the case label that matches the condition is executed. In case, no case label that matches the condition, the block of code corresponding to the default label is executed.

In C++, we use curly bracket { } to indicate the start and end of the loop body.

Explore free C++ courses

NOTE:

  • C++ is case-sensitive. The switch-case is in lowercase letters, using Switch-Case or SWITCH-CASE will result in an error.

Below, we have illustrated the switch statement flowchart –

2022_08_switch-statement-in-c-plus-plus.jpg
Recommended online courses

Best-suited C++ courses for you

Learn C++ with these high-rated online courses

– / –
4 months
4.24 K
6 weeks
– / –
15 days
– / –
– / –
7.14 K
5 weeks
name
SoloLearnCertificateStar Icon4.5
Free
– / –
– / –
4 months
– / –
3 months

C++ Switch Statement Implementation Examples

Example 1: Build a Calculator Using Switch Statement in C++


 
#include
using namespace std;
int main() {
char op;
int a , b;
cout << "Select the operation you would like to perform (+, -, *, /, %): ";
cin >> op;
cout << "Enter two numbers: " << endl;
cin >> a >> b;
switch (op) {
case '+':
cout << a << " + " << b << " = " << a + b;
break;
case '-':
cout << a << " - " << b << " = " << a - b;
break;
case '*':
cout << a << " * " << b << " = " << a * b;
break;
case '/':
cout << a << " / " << b << " = " << a / b;
break;
case '%':
cout << a << " % " << b << " = " << a % b;
break;
default:
cout << "The operator is not valid. Please choose from the given list.";
break;
}
return 0;
}
Copy code

Output 1:


 
Select the operation you would like to perform (+, -, *, /, %): +
Enter two numbers:
7
3
7 + 3 = 10
Copy code

Output 2:


 
Select the operation you would like to perform (+, -, *, /, %): %
Enter two numbers:
7
3
7 % 3 = 1
Copy code

Output 3:


 
Select the operation you would like to perform (+, -, *, /, %): $
Enter two numbers:
7
3
The operator is not valid. Please choose from the given list.
Copy code
All About C++ Friend Function
7 Enticing Ways To Improve Your Coding Skills
Introduction to QuickSort Algorithm in C++

What have we done here?

  • First, we prompt the user to enter an operator from the given list ( + , – , * , / , % ). The entered input is stored in the char type variable op.
  • The use then enters two numbers (operands) on which the mathematical operation will be performed. These numbers are stored in the int type variables a and b.
  • Then, the switch statement is used to evaluate the operator entered by the user:
    • If the user enters +, addition is performed, and the sum is printed.
    • If the user enters -, subtraction is performed, and the difference is printed.
    • If the user enters *, multiplication is performed, and the product is printed.
    • If the user enters /, the division is performed, and the quotient is printed.
    • If the user enters %, modulus operation is performed, and the remainder is printed.
    • If the user enters any other symbol than the ones described above, the expression evaluates to be False and the default code is executed.

NOTE:

  • We use the break statement inside each case block to terminate the switch statement once the calculation is performed and the result is printed. If the break statement is not present, the control will be given to the next case label and in this way, all the case blocks after the correct case will also be executed.
  • The default statement is optional.
  • Nesting of switch statements is allowed. However nested statements increase the complexity of the program and affect its readability, hence one should avoid using nested statements and loops unless necessary.

Example 2: Write a C++ Program that returns the day of the week corresponding to the number.


 
#include
using namespace std;
class day
{
private:
int day;
public:
void day_num()
{
cout << "Enter the day number: ";
cin >> day;
}
void day_name()
{
switch (day)
{
case 1:
cout<<"Monday is the 1st day of the week";
break;
case 2:
cout<<"Tuesday is the 2nd day of the week";
break;
case 3:
cout<<"Wednesday is the 3rd day of the week";
break;
case 4:
cout<<"Thursday is the 4th day of the week";
break;
case 5:
cout<<"Friday is the 5th day of the week";
break;
case 6:
cout<<"Saturday is the 6th day of the week";
break;
case 7:
cout<<"Sunday is the 7th day of the week";
break;
default:
cout<<"Invalid Input Number!";
break;
}
}
};
//Driver code
main()
{
day d1;
d1.day_num();
d1.day_name();
return 0;
}
Copy code

Output 1:


 
Enter the day number: 6
Saturday is the 6th day of the week
Copy code

Output 2:


 
Enter the day number: 10
Invalid Input Number!
Copy code

Endnotes

Hope this article was helpful for you to understand the switch case statements and how they are used to perform decision-making in C++. If you want to learn more about this programming language and solidify your basics, you can explore our articles on C++.

_______________

Recently completed any professional course/certification from the market? Tell us what you liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online

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