Calculator Program in C++ using Switch Case

In this C++ programming tutorial we will see create a Calculator Program in C++ using Switch Case statements. The program will accept 2 numbers from user and then give an option of the operation that the user wants to perform. This program will perform the following operations : Addition(+), Subtraction(-), Multiplication(*) & Division(/). Once the user enters the appropriate sign, the corresponding switch case block will be executed and the output will be shown.

Calculator Program in C++ using Switch Case
#include <iostream>
using namespace std;

int main() {
    char o;
    float num1,num2;
    cout<<"Enter two numbers: ";
    cin>>num1>>num2;
    cout<<"Select an operator either + or - or * or / \n";
    cin>>o;
    
    
    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 */
            cout<<"Error! operator is not correct";
            break;
    }
    
	return 0;
}
Output
Enter 2 numbers: 5 10
Select an operator either + or – or * or /
+
5 + 10 = 15

Leave a Reply

Your email address will not be published. Required fields are marked *