Switch Statement Sample

A switch statement sample is a selection control mechanism in programming that is used to perform selective parts of a program code depending on a specified value. Just like an If Else statement, this statement is helpful and is much useful and easy to implement when testing a single variable. A switch statement contains three parts as shown below.

General syntax of a switch statement sample

Switch (integer or variable expression)

{

Case 1:

Code to execute

break;

Case 2:

                Code to execute

break;

Case 3:

                Code to execute

                break;

default:

                Code to execute

}

 

A Switch Statement Flow Diagram/ Flow Chart

Switch Statement Sample in C++ programming Language

#include <iostream>

using namespace std;

 

int main()

{

    char operator;

    float operand1, operand2;

 

    cout << “Choose an operator from these (+, -, *, /): “;

    cin >> operator;

 

    cout << “Enter first operand: “;

    cin >> operand2;

    cout << “Enter second operand: “;

    cin >> operand2;

   

    switch (operator)

    {

        case ‘+’:

            cout << operand1<< ” + ” << operand2<< ” = ” << operand1+ operand2;

            break;

        case ‘-‘:

            cout << operand1<< ” – ” << operand2<< ” = ” << operand1- operand2;

            break;

        case ‘*’:

            cout << operand1<< ” * ” << operand2<< ” = ” << operand1* operand2;

            break;

        case ‘/’:

            cout << operand1<< ” / ” << operand2<< ” = ” << operand1/ operand2;

            break;

        default:

            // In case the operator is does not match any case constant (+, -, *, /)

            cout << “Error! Incorrect operator”;

            break;

    }

        return 0;

}

The above code is a simple C++ code that performs an operation selected by a user on two chosen operands and displays the result. When the user chooses “+” the block of code in case 1 in executed, the addition of the two operands. Each case is executed depending on the operator chosen(Switch Statement Sample).

Need an assignment done for you on this topic? click on PLACE ORDER and fill the form