Course Content
C++ Introduction
0/1
C++ Variables & Constants
0/1
C++Scope of Variable
0/1
C++ Keywords & Identifiers
0/1
C++ Data Types
0/1
C++ Basic I/O
0/1
C++ Type Conversion
0/1
C++ Operators
0/1
C++ Comments
0/1
C++ If-else
0/1
C++ Ternary Operator
0/1
C++ for Loop
0/1
C++ Ranged for Loop
0/1
C++ while/do-while Loop
0/1
C++ break Statement
0/1
C++ Continue Statement
0/1
C++ switch Statement
0/1
C++ goto Statement
0/1
C++ Functions
0/1
C++ User-defined Functions
0/1
C++ Default Arguments
0/1
C++ Storage Class
0/1
C++ Recursion
0/1
C++ Return by Reference
0/1
C++ Arrays
0/1
C++ Multi-dimentional Arrays
0/1
C++ Arrays & Function
0/1
C++ String
0/1
C++ Structure
0/1
C++ Structure & Functions
0/1
C++ Pointers to Structure
0/1
C++ Pointers
0/1
C++ Void Pointers
0/1
C++ Pointers & Arrays
0/1
C++ Pointers & Functions
0/1
C++ Dynamic Memory Allocation
0/1
C++ OOPs Concepts
0/1
C++ Objects and Class
0/1
C++ Constructors
0/1
C++ Destructors
0/1
C++ Constructor Overloading
0/1
C++ Objects & Function
0/1
C++ Enumeration
0/1
C++ Inheritance
0/1
C++ Inheritance Access Control
0/1
C++ Inheritance Types
0/1
C++ Polymorphism
0/1
C++ Function Overloading
0/1
C++ Function Overriding
0/1
C++ Operator Overloading
0/1
C++ Friend Function
0/1
C++ Virtual Function
0/1
C++ Abstract Class & Pure Virtual Function
0/1
C++ Encapsulation
0/1
C++ Abstraction
0/1
C++ Templates
0/1
C++ Exception Handling
0/1
C++ Multithreading
0/1
C++ Standard Library
0/1
C++ Programming Tutorials
About Lesson

C++ Switch Statement

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


Switch Statement

Switch case statements are controlles statement that is regarded as a substitute for if-else statements. Switch statements are used for long if-else statements that compare a variable to several integral values.

The Switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Switch is a control statement that allows a value to change control of execution.


Syntax: Switch Case Statement

The switch statement allows us to execute a block of code among many alternatives.

switch (expression)  {
    case 1:
    // code to be executed if the expression is equal to case 1
    // break statement execute
    break;

    case 2:
    // code to be executed if the expression is equal to case 2
    // break statement execute
    break;
    .
    .
    default:
    // code to be executed if the expression doesn't match any case
}

You need to keep things in mind when using a Switch Statement:

  1. The expression provided in the switch must be a constant value otherwise it is invalid.
  2. Duplicate case values are not allowed.
  3. The default statement is optional. Even if the switch case statement do not have a default statement, it would work without any problem.
  4. The break statement is used to take control out of the loop otherwise all the cases before a break would be executed.
  5. break statement is used inside the switch to terminate a statement sequence. When a break statement is reached , the switch terminates, and the flow of control jumps to next line following the switch statement.
  6. The break statement is optional. If omitted, execution will continue on into the next case. The flow of control will fall though to subsequent cases until a break is reached.
  7. The switch statement can also be nested, which means you have switch statements inside another switch.

Flowchart of switch Statement

C++ switch...case flowchart
Flowchart of C++ switch…case statement

How does the switch statement work?

The expression is evaluated once and compared with the values of each case label.

  • The value of this expression is then compared with the first case. if the first case matches then the block of code associated with the first case is executed.
  • Once the break is encountered, the execution stops and the switch statement terminates.
  • However, if the case does not match, the execution flows to the next case.
  • If this case matches, then the second code block executes otherwise, the flow checks the next case.
  • In case the value is not equal, the code after default: is executed.

Note: We can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is cleaner and much easier to read and write.


Example 1: C++ Program to understand the switch Statement

//  a simple program to understand switch Statement
#include <iostream>
using namespace std;
int main() {
    int a = 1;

    switch (a) {
        case 1:
            cout << n1 << "My Choice is 1";
            break;
        case 2:
            cout << n1 << "My Choice is 2";
            break;
        case 3:
            cout << n1 << "My Choice is 3";
            break;
        default:
            // Variable "a" doesn't match any case
            cout << "Invalid! The Choice is not correct";
            break;
    }
    return 0;
}

Output

My Choice is 1

Example 2: C++ Create a Calculator using the switch Statement

// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;
int main() {
    char operator;
    float n1, n2;
    cout << "Enter an operator (+, -, *, /): ";
    cin >> oper;
    cout << "Enter two numbers: " << endl;
    cin >> n1 >> n2;

    switch (operator) {
        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 << "Invalid! The operator is not correct";
            break;
    }
    return 0;
}

Output

Enter an operator (+, -, *, /): +
Enter two numbers: 
5
3
5 + 3 = 8

Output 2

Enter an operator (+, -, *, /): -
Enter two numbers: 
5
3
5 - 2 = 3

Output 3

Enter an operator (+, -, *, /): *
Enter two numbers: 
5
2
5 * 2 = 10

Output 4

Enter an operator (+, -, *, /): /
Enter two numbers: 
6
2
6 / 2 = 3

Output 5

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

In the above program, we are using the switch...case statement to perform addition, subtraction, multiplication, and division.


How This Program Works

  1. We first prompt the user to enter the desired operator. This input is then stored in the char variable named oper.
  2. We then prompt the user to enter two numbers, which are stored in the float variables n1 and n2.
  3. The switch statement is then used to check the operator entered by the user:
    • If the user enters +, addition is performed on the numbers.
    • If the user enters -, subtraction is performed on the numbers.
    • If the user enters *, multiplication is performed on the numbers.
    • If the user enters /, division is performed on the numbers.
    • If the user enters any other character, the default code is printed.

Notice that the break statement is used inside each case block. This terminates the switch statement.

If the break statement is not used, all cases after the correct case are executed.

Exercise Files
No Attachment Found
No Attachment Found
error: Content is protected !!