C++ Program to Make a Calculator using Switch Case.

In this post, we are going to understand how to write simple calculator program in C++ programming language using switch and break statement. 

Make a Calculator using Switch Case

Our calculator can perform operation like addition, substraction, multiplication and division. It is going to take two input value from the user and the arthematic operator as a single character to perform that particular operation of the input values. 

C++ Example Code for Calculator using Switch statement. 

//C++ Code to make calculator using switch statement
#include<iostream>
using namespace std;

int main(){

    float value1, value2, result;
    char opt;

    cout<<"Enter two values: ";
    cin>>value1>>value2;
    cout<<"Enter the operator: ";
    cin>>opt;

    switch (opt)
    {
    case '+':
        result = value1 + value2;
        cout<<value1<<" + "<<value2<<" = "<<result<<endl;
        break;
    case '-':
        result = value1 - value2;
        cout<<value1<<" - "<<value2<<" = "<<result<<endl;
        break;
    case '*':
        result = value1 * value2;
        cout<<value1<<" * "<<value2<<" = "<<result<<endl;
        break; 
    case '/':
        result = value1 / value2;
        cout<<value1<<" / "<<value2<<" = "<<result<<endl;
        break;       
    default:
        cout<<"Operator not found !!!"<<endl;
        break;
    }
    return 0;
}
Output:
Enter two values: 56 4
Enter the operator: /
56 / 4 = 14

In the above program, we use switch case to check which kind of operator user in providing as an input and based on the correct match of switch we are executing the piece of code written in that particular case. 

Once the operation is performed and it reach the break statement we come out of switch case statements and end the code execution. If any chance we enter any wrong and invalid operator then the default section of switch case will execute. 

Next:

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS