How to Write a Simple Calculator Program using C++ Programming language

Here we are writing a Calculator Program using C++ Programming language.

This is one of the simplest program a beginner can write and understand a lot about computer programming.

The Calculator Program that we are writing here will work on two numbers and it will support Addition, Subtraction, Multiplication and Division operations.

Program Source Code : Calculator.cpp

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 int main(){
 6 
 7     char op;
 8     double num1,num2;
 9 
10     cout << "Enter the Operator ( +, -, *, / ) : ";
11     cin >> op;
12 
13     cout << "Enter two numbers one by one : ";
14     cin >> num1 >> num2;
15 
16     switch ( op ){
17 
18         case '+':
19             cout << num1 << " + " << num2 << " = " << (num1 + num2);
20             break;
21 
22         case '-':
23             cout << num1 << " - " << num2 << " = " << (num1 - num2);
24             break;        
25 
26         case '*':
27             cout << num1 << " * " << num2 << " = " << (num1 * num2);
28             break;
29 
30         case '/':
31             if( num2 != 0.0 )
32                 cout << num1 << " / " << num2 << " = " << (num1 / num2);
33             else 
34                 cout << "Divide by zero situation";
35 
36             break;
37 
38         default:
39             cout << op << " is an invalid operator";
40     }
41  
42     return 0;
43 }

Program Output : Run 1

Enter the Operator ( +, -, *, / ) : +
Enter the two Numbers one by one : 10 20
10 + 20 = 30

Program Output : Run 2

Enter the Operator ( +, -, *, / ) : -
Enter the two Numbers one by one : 10 30
10 - 30 = -20

Program Output : Run 3

Enter the Operator ( +, -, *, / ) : *
Enter the two Numbers one by one : 10 50
10 * 50 = 500

Program Output : Run 4

Enter the Operator ( +, -, *, / ) : /
Enter the two Numbers one by one : 10 20
10 / 20 = 0.5

Program Output : Run 5

Enter the Operator ( +, -, *, / ) : /
Enter the two Numbers one by one : 50 0
Divide by Zero situation

Program Output : Run 6

Enter the Operator ( +, -, *, / ) : ?
Enter the two Numbers one by one : 10 20
? is an invalid Operator

Video Tutorial : How to Write a Simple Calculator Program using C++ Programming language