Calculator Program in C++
Written by
Program to make basic calculator
This can be done by simply using the switch case where the cases will be the operators (+,-,*,/).
Algorithm
- Prompt the user to enter two operands on which to perform the operation.
- Prompt the user to enter the operator to use.
- Use a switch statement to check if the operator matches any of the cases ('+', '-', '*', '/'). If the operator does not match any of these cases, display an error message.
- If the operator does match one of the cases, perform the corresponding operation on the operands and print the result.
Code
// C++ program to create calculator
#include <iostream>
using namespace std;
// Main program
int main() {
char oper;
float a, b;
// It allow user to enter the operands
cout << "Enter two operands: ";
cin >> a >> b;
// It allows user to enter operator i.e. +, -, *, /
cout << "Enter operator: ";
cin >> oper;
// Switch statement begins
switch (oper) {
// If operator is '+'
case '+':
cout << a + b;
break;
// If operator is '-'
case '-':
cout << a - b;
break;
// If operator is '*'
case '*':
cout << a * b;
break;
// If operator is '/'
case '/':
cout << a / b;
break;
// If any other operator display error message
default:
cout << "Error! Incorrect operator";
break;
}
return 0;
}
Output
Input:
Enter two operands: 10 20
Enter operator: *
Output:
200