Coding a Basic Calculator in C++

Exercise:

Write a C++ program that creates an ordinary calculator which can perform simple functions like addition, subtraction, multiplication, and division with the help of switch case.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    char opr;
    float num1, num2;
    cout << "Insert an operator (+ , - , * , /):\n";
    cin >> opr;
    cout << "Insert both operands:\n";
    cin >> num1 >> num2;
    cout<<endl;
    switch(opr)
    {
       case '-':
         cout << num1<<" "<<opr<<" "<<num2<<" = "<<num1-num2;
         break;
       case '+':
         cout << num1<<" "<<opr<<" "<<num2<<" = "<< num1+num2;
         break;
       case '*':
         cout << num1<<" "<<opr<<" "<<num2<<" = "<< num1*num2;
         break;
       case '/':
         cout << num1<<" "<<opr<<" "<<num2<<" = "<< num1/num2;
         break;
       default:
    // If the operator is other than +, -, * or /, show an error message
         cout << "ERROR! operator not found";
         break;
    } 
    return 0;
}
Click Here to View the Output:
Insert an operator (+ , - , * , /):
/
Insert both operands:
56.64
5.55
56.64 / 5.55 = 10.2054
Click Here to View the Explanation:
  • An operator and 2 numbers (operands) are requested to be inserted by the user num1 and num2, and opr saves the operator, a char type variable.
  • Operator entered by the user is checked through switch... case statement switch (opr).
  • In case the user selects *, num1 and num2 are multiplied with each other because statements for case '*' are executed. Similarly, switch cases statements are applied for +, - and /.
  • If some other character is inserted, the error message is printed on the screen.
%d bloggers like this: