C++ Program to Make a Simple Calculator Using Switch Case Statement

  • Write a C++ program to make a simple calculator for addition, subtraction, multiplication and division using switch case statement.

In this C++ Program, we will make a simple calculator using switch case statement to perform basic arithmetic operations like Addition, Subtraction, Multiplication and Division of two numbers. Before jumping into program, we need a basic understanding of arithmetic operators of C++.

An arithmetic operator is a symbol used to perform mathematical operations in a C++ program. The four fundamental arithmetic operators supported by C++ language are addition(+), subtraction(-), division(/) and multiplication(*) of two numbers.

Operator Description Syntax Example
+ Adds two numbers a + b 15 + 5 = 20
- Subtracts two numbers a - b 15 - 5 = 10
* Multiplies two numbers a * b 15 * 5 = 75
/ Divides numerator by denominator a / b 15 / 5 = 3

C++ Program to Make a Simple Calculator using Switch Case Statement

// C++ program to make a simple calculator to Add, Subtract, 
// Multiply or Divide using switch...case statement
#include <iostream>
using namespace std;
 
int main() {
    char op;
    float num1, num2;
     
    cout << "Enter an arithemetic operator(+ - * /)\n";
    cin >> op;
    cout << "Enter two numbers as operands\n";
    cin >> num1 >> num2;
 
    switch(op) {
        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: 
                printf("ERROR: Unsupported Operation");
    }
     
    return 0;
}
Output
Enter an arithemetic operator(+ - * /)
+
Enter two numbers as operands
2 8
2 + 8 = 10
Enter an arithemetic operator(+ - * /)
*
Enter two numbers as operands
3 7
3 * 7 = 21

In above program, we first take an arithmetic operator as input from user and store it in a character variable op. Our calculator program only support four basic arithmetic operators, Addition(+), Subtraction(-), Multiplication(*) and Division(/). Then we take two integers operands as input from user and store it in variable num1 and num2.

We are using switch case statement for selecting appropriate arithmetic operation. Based on the operator entered by the user(+, -, * or /), we perform corresponding calculation and print the result on screen using cout.

If the arithmetic operator entered by the user doesn't match with '+', '-', '*' or '/' then default case block will print an error message on screen.