C++ Program to Make a Simple Calculator
Last Updated :
21 Sep, 2023
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++.
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++
#include <iostream>
using namespace std;
int main()
{
char op;
float num1, num2;
cin >> op;
cin >> num1 >> num2;
switch (op) {
case '+' :
cout << num1 + num2;
break ;
case '-' :
cout << num1 - num2;
break ;
case '*' :
cout << num1 * num2;
break ;
case '/' :
cout << num1 / num2;
break ;
default :
cout << "Error! operator is not correct" ;
}
return 0;
}
|
Input
+
2
2
Output
4
Complexity Analysis
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...