C++ Program to Make a Simple Calculator to Add, Subtract, Multiply or Divide Using switch...case

To understand this example, you should have the knowledge of the following C++ programming topics:


This program takes an arithmetic operator (+, -, *, /) and two operands from a user and performs the operation on those two operands depending upon the operator entered by the user.


Example: Simple Calculator using switch statement

# include <iostream>
using namespace std;

int main() {

  char op;
  float num1, num2;

  cout << "Enter operator: +, -, *, /: ";
  cin >> op;

  cout << "Enter two operands: ";
  cin >> num1 >> num2;

  switch(op) {

    case '+':
      cout << num1 << " + " << num2 << " = " << num1 + num2;
      break;

    case '-':
      cout << num1 << " - " << num2 << " = " << num1 - num2;
      break;

    case '*':
      cout << num1 << " * " << num2 << " = " << num1 * num2;
      break;

    case '/':
      cout << num1 << " / " << num2 << " = " << num1 / num2;
      break;

    default:
      // If the operator is other than +, -, * or /, error message is shown
      cout << "Error! operator is not correct";
      break;
  }

  return 0;
}

Output

Enter operator: +, -, *, /: -    
Enter two operands: 3.4 8.4
3.4 - 8.4 = -5

This program takes an operator and two operands from the user.

The operator is stored in variable op and two operands are stored in num1 and num2 respectively.

Then, switch...case statement is used for checking the operator entered by user.

If user enters + then, statements for case: '+' is executed and program is terminated.

If user enters - then, statements for case: '-' is executed and program is terminated.

This program works similarly for the * and / operators. But, if the operator doesn't matches any of the four character [ +, -, * and / ], the default statement is executed which displays error message.


Also Read:

Before we wrap up, let's put your understanding of this example to the test! Can you solve the following challenge?

Challenge:

Write a function to perform basic arithmetic operations.

  • Return the result of the operation specified by operator on the numbers num1 and num2.
  • The operations are: addition +, subtraction -, multiplication *, and division /.
  • For example, if num1 = 5, op = '+', and num2 = 3, the return value should be 8.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges