C++ Program to Implement a Simple Calculator

Below is the C++ program to make a simple calculator using switch and break statements:

C++




// C++ program to create calculator using
// switch statement
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
    char op;
    float num1, num2;
 
    // It allows user to enter operator
    // i.e. +, -, *, /
    cin >> op;
 
    // It allow user to enter the operands
    cin >> num1 >> num2;
 
    // Switch statement begins
    switch (op) {
    // If user enter +
    case '+':
        cout << num1 + num2;
        break;
 
    // If user enter -
    case '-':
        cout << num1 - num2;
        break;
 
    // If user enter *
    case '*':
        cout << num1 * num2;
        break;
 
    // If user enter /
    case '/':
        cout << num1 / num2;
        break;
 
    // If the operator is other than +, -, * or /,
    // error message will display
    default:
        cout << "Error! operator is not correct";
    }
    // switch statement ends
 
    return 0;
}


Input

+
2
2

Output

4

Complexity Analysis

Time Complexity: O(1)
Auxiliary Space: O(1)



C++ Program to Make a Simple Calculator

A simple calculator is a device used to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. It makes arithmetic calculations easier and faster. In this article, we will learn how to code a simple calculator using C++.

Similar Reads

Algorithm to Make a Simple Calculator

Initialize two float variables num1 and num2 to take two operands as input. Initialize a char variable op to take the operator as input. Start the switch statement with op as the expression of the switch statement. Now, create cases for different arithmetic operations. ‘+’ for addition ‘-‘ for subtraction ‘*’ for multiplication ‘/’ for division Default case for the case when the entered operator is not one of the above operators. The operation will be performed based on the operator entered as the input....

C++ Program to Implement a Simple Calculator

Below is the C++ program to make a simple calculator using switch and break statements:...

Contact Us