You are currently viewing C++ switch case statement with Example | C++ Programming

C++ switch case statement with Example | C++ Programming

In this tutorial, we will learn about switch case statement and their working in C++ programming with the help of some examples.

The switch statement allows us to choose among a number of different ways to run a block of code.

In C++, the switch statement has the following syntax:

switch (expression)
{
case 1:
break;
case 2:
if n = 2;
break;
default: // code to be executed if n doesn’t match any cases
}

  • Long if statements that compare a variable to numerous integral values can be replaced with switch-case statements.

The Following Are Some Important Switch case Statement Rules:

  • Case values that are duplicated are not permitted.
  • A case value must be a constant or a literal. Variables are not permitted.
  • A case value must be the same data type as the variable in the switch.
  • To end a statement sequence, use the break statement inside the switch.
  • The break statement is not required. If this field is left blank, execution will proceed to the next case.
  • The default statement is optional and can appear at any point within the switch block. If it is not at the end, a break statement must be added after the default statement to prevent the next case statement from being executed.

A multiway branch statement is the switch statement. It makes it simple to route execution to different areas of code based on the expression’s value.

A switch statement is a control statement that allows a value to shift execution control.

Working of Switch case statements

  • Only one time is the switch expression evaluated.
  • The expression’s value is compared to the values of each case.
  • If a match is found, the relevant code block is run.
  • The keywords break and default are optional and will be discussed later in this chapter.
#include <iostream>
using namespace std;

int main() {
int x = 2;
	switch (x)
	{
		case 1:
			cout << "Choice is 1";
			break;
		case 2:
			cout << "Choice is 2";
			break;
		case 3:
			cout << "Choice is 3";
			break;
		default:
			cout << "Choice other than 1, 2 and 3";
			break;
	}
return 0;
}

Keyword: (Break)

More code and case testing will not be executed inside the block as a result of this.

  • It’s time to take a break once you’ve discovered a match and finished the task. More testing is not required.
  • Because it “ignores” the execution of the rest of the code in the switch block, a break can save a lot of time.
#include <iostream>
using namespace std;

int main() {
        int x=3;
        switch(x)
        {
            case 1:
                cout<<"Kotlin used in Android development";
                break;
            case 2:
                cout<<"Java used in Mobile App Development, Desktop GUI Applications, Web-based Applications";
                break;
            case 3:
                cout<<"C ++ used in web browsers, database";
                break;
            
        }
    }
}

Output:

C ++ used in web browsers, database

Keyword: (default)

If there is no case match, the default keyword defines some code to run:

#include <iostream>
using namespace std;
int day = 4;
switch (day) {
  case 6:
    cout << "Today is Saturday";
    break;
  case 7:
    cout << "Today is Sunday";
    break;
  default:
    cout << "Looking forward to the Weekend";
}

Output

Looking forward to the Weekend

Switch case Example: Create a calculator using the switch statement as an example

// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main() {
    char o;
    float n1, n2;
    cout << "Enter an operator (+, -, *, /): ";
    cin >> o;
    cout << "Enter two numbers: " << endl;
    cin >> n1 >> n2;

    switch (o) {
        case '+':
            cout << n1 << " + " << n2 << " = " << n1 + n2;
            break;
        case '-':
            cout << n1 << " - " << n2 << " = " << n1 - n2;
            break;
        case '*':
            cout << n1 << " * " << n2 << " = " << n1 * n2;
            break;
        case '/':
            cout << n1 << " / " << n2 << " = " << n1 / n2;
            break;
        default:
            // operator is doesn't match any case constant (+, -, *, /)
            cout << "Error! The operator is not correct";
            break;
    }

    return 0;
}

Output 1:

Enter an operator (+, -, *, /): +
Enter two numbers:
2.3
4.5
2.3 + 4.5 = 6.8

Output 2:

Enter an operator (+, -, *, /): –
Enter two numbers:
2.3
4.5
2.3 – 4.5 = -2.2

Output 3:

Enter an operator (+, -, *, /): *
Enter two numbers:
2.3
4.5
2.3 * 4.5 = 10.35

Output 4:

Enter an operator (+, -, *, /): /
Enter two numbers:
2.3
4.5
2.3 / 4.5 = 0.511111

Output 5:

Enter an operator (+, -, *, /): ?
Enter two numbers:
2.3
4.5
Error! The operator is not correct.

Nested Switch Case statement

Another switch statement can be used inside a switch statement. In C++, this is referred to as nested switch-case statements. The inner switch statement will be included in any situation of an outside switch. Only if the outer switch statement condition is true will the inner switch statement be executed.

switch(n)
{
//if n = 1;
case 1:
// ******************Nested switch*********************
switch(num)
{
//if num = 10
case 10:
statement 1;
break;
//if num = 20
case 20:
statement 2;
break;
//if num = 30
case 30:
statement 3;
break;
// doesn’t match any cases
default:
}

// syntax of Nested Switch Statements.
#include <iostream>
using namespace std;

int main()
{
	int x = 1, y = 2;
	// Outer Switch
	switch (x) {

	// If x == 1
	case 1:

		// Nested Switch

		switch (y) {

		// If y == 2
		case 2:
			cout << "Choice is 2";
			break;

		// If y == 3
		case 3:
			cout << "Choice is 3";
			break;
		}
		break;

	
	default:
		cout << "Choice is other than 1, 2 3, 4, or 5";
		break;
	}
	return 0;
}

Switch case Enum Example: A C++ program that demonstrates the use of a switch case with an enum

#include <iostream>
#include <string>
#include <map>
using namespace std;

enum level {easy, medium, hard};
map<string, level> levels;

void register_levels()
{
    levels["easy"]   = easy;
    levels["medium"] = medium;
    levels["hard"]   = hard;
}

int main()
{
    register_levels();
    string input;
    cin >> input;
    switch( levels[input] )
    {
    case easy:
        cout << "easy!"; break;
    case medium:
        cout << "medium!"; break;
    case hard:
        cout << "hard!"; break;
    }
}

Few points about the Switch Case

switch case C++ ,switch case C++ ,switch case C++ ,switch case C++ ,switch case C++ ,switch case C++ ,switch case C++ ,switch case C++ ,switch case program in C++ switch case program in C++ switch case program

When using switch case statements in C++, there are a few rules that must be followed.

  • In a switch case statement, case values can only be integersstrings, or enums.
  • A switch-case block can contain an unlimited number of cases. You are free to have as many as you want. Each case block is preceded by the case value and a colon( : ). The code that will be executed when the case is true follows.
  • Keep in mind that the value and data type must be the same as the variable in the switch block.
  • Cases do not allow for expressions. The value can only be literal or constant.
  • When a case evaluates to true, the compiler will execute each statement line by line until it encounters a break statement.
  • The control shifts to the lines following the switch block as soon as the compiler passes through a break statement.
  • The switch case in C++ is a fall-through case. This means that if no break statement is present in a case block, the program’s control will continue to loop through all of the cases.
  • If no case evaluates to true, the default case (if it exists) is executed.
  • Each case value must be unique.

You may like:

Operators In C++ Programming

if…else – Nested if…else | C++ Programming

This Post Has 2 Comments

Leave a Reply