C++ | Switch Statement

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

We will also build a simple calculator with operations like addition, subtraction, multiplication, and division using the switch and break statement.

Switch Statement

A switch statement works on a choice that is it works like a selection statement. The given expression is evaluated and based on the value; it executes the statements associated with it. It is used to perform different operations/actions based on different conditions (cases).

The main points to be remembered about the switch statements are:

  • The switch statements follow a selection-control mechanism and allow certain values to decide the change of control of the execution.
  • It is a substitute for long if-else statements for checking multiple conditions.
  • This statement is a multi-way decision-making statement, which executes different parts of the code depending on the value of the expression.

The switch statement along with the conditional-based cases also has a default case which will be executed when the evaluated value does not match any of the case values.

In the switch statement, the case value can either be a character value (char) or an integer value (int).

We must follow some rules in order to use a switch statement:

  1. There can be a 1 to N number of cases in a switch statement.
  2. All the case values must be unique.
  3. Mostly we use break statements for every case but they are optional

Syntax:

Example:

#include<iostream>
using namespace std;
int main()
{
    int day;
    cout<<"Enter no of day you want to display: ";
    cin>>day;   
    switch (day){             
        case 1:
            cout<<"MONDAY";
            break;
        case 2:
            cout<<"TUESDAY";
            break;
        case 3:
            cout<<"WEDNESDAY";
            break;
        case 4:
            cout<<"THURSDAY";
            break;
        case 5:
            cout<<"FRIDAY";
            break;
        case 6:
            cout<<"SATURDAY";
            break;
        case 7:
            cout<<"SUNDAY";
            break;
        default:
            cout<<"INVALID INPUT";
            break;
    }
    return 0;
}

Output:

See also  Function in c++

Enter no of day you want to display: 6

SATURDAY

Flow Chart of switch statement:

Output:

Enter no of day you want to display: 6

SATURDAY

Flow Chart of switch statement:

break statement:

In the switch statement, the break statement is used in each case to break out of the switch block after the required block is executed. The break statement will stop the execution of more code and case testing inside the switch block.

A break statement can save a lot of execution time because it ignores the execution of all the remaining code in the switch block.

Default keyword:

 The default keyword specifies some code that is to be executed if no case is matched.

Example:

#include<iostream>
using namespace std;
int main()
{
    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";
}
    return 0;
}

Output:

 Looking forward to the Weekend 

Simple Calculator Using Switch:

Now that we know what a switch statement is and how we use it, let’s now write a program to create a simple calculator using the switch statement along with the break statement and the default keyword.

Code Implementation:

First, we include the iostream file and also specify the namespace that is the std (standard) namespace to use the cin and cout objects like we do in every C++ program we write.

See also  INHERITANCE IN C++

#include <iostream>

using namespace std;

#include <iostream>
using namespace std;

After that, we define the main method and inside that, we write the code for our simple calculator.

We first declare a variable to take input from the user and store the operation that the user wants to perform.

Along with that declaration, we also declare two other variables of float type to take the input and store the values on which we want to perform the chosen operation.

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

After declaring and taking the inputs from the user we write code for the calculation using the switch statement. As we have taken a char type variable as an input in the case value we will be giving the character values only.

According to the option entered a certain operation is performed and the result is printed. If the user enters an invalid option then a message will be displayed saying “Error! The operator is not correct”.

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

    return 0;
}

Source Code:

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

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

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

Output:

That is all for this article. Hope learned something new from this article.

See also  TYPES OF FUNCTIONS IN C++

Happy Coding!

Leave a Comment

Your email address will not be published.

Ads Blocker Image Powered by Code Help Pro
Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Refresh