Horje
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++.

Pictorial Representation of Simple Calculator

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:

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)




Reffered: https://www.geeksforgeeks.org


C++ Programs

Related
Difference between continue and break statements in C++ Difference between continue and break statements in C++
upper_bound and lower_bound for non increasing vector in c++ upper_bound and lower_bound for non increasing vector in c++
Possible number of Rectangle and Squares with the given set of elements Possible number of Rectangle and Squares with the given set of elements
Convert time from 24 hour clock to 12 hour clock format Convert time from 24 hour clock to 12 hour clock format
Degree of a Cycle Graph Degree of a Cycle Graph

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
9