fastread homefastrread library fastread menu

C++ : Switch Statement

Tutorial by:Manisha Dubey      Date: 2016-06-18 00:04:11

❰ Previous Next ❱

Consider a situation in which, only one block of code needs to be executed among many blocks. This type of situation can be handled using nested if...else statement but, the better way of handling this type of problem is using switch...case statement.

Syntax of switch

switch (n) {
case constant1:
   code/s to be executed if n equals to constant1;
   break;
case constant2:
   code/s to be executed if n equals to constant2;
   break;
   .
   .
   . 
default:
   code/s to be executed if n doesn't match to any cases;
}

The value of n is either an integer or a character in above syntax. If the value of n matches constant in case, the relevant codes are executed and control moves out of the switch statement. If the n doesn't matches any of the constant in case, then the default statement is executed and control moves out of switch statement.

Flowchart of switch Statement

Flowchart of switch case statement in C++ Programming

Example 1: C++ switch Statement

/* C++ program to demonstrate working of switch Statement */
/* C++ program to built simple calculator using switch Statement */


#include <iostream>
using namespace std;
int main() {
    char o;
    float num1,num2;
    cout<<"Select an operator either + or - or * or / \n";
    cin>>o;
    cout<<"Enter two operands: ";
    cin>>num1>>num2;
    
    switch(o) {
        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:
            
            /* If operator is other than +, -, * or /, error message is shown */
            printf("Error! operator is not correct");
            break;
    }
    
    return 0;
}

 

 
 

Output


Select an operator either + or - or * or / 
-
Enter two operands: 2.3
4.5
2.3 - 4.5 = -2.2

The break statement at the end of each case cause switch statement to exit. If break statement is not used, all statements below that case statement are also executed.

❰ Previous Next ❱


C++

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website