Write a Simple program in C++ for Calculator to Add, Subtract, Multiply, and Divide two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include <iostream> using namespace std; int main() { char op; double num1, num2; // Prompt the user to enter the operator cout << "Enter operator (+, -, *, /): "; cin >> op; // Prompt the user to enter two operands cout << "Enter two numbers: "; cin >> num1 >> num2; // Perform the appropriate operation based on the operator entered switch (op) { case '+': cout << num1 << " + " << num2 << " = " << num1 + num2 << endl; break; case '-': cout << num1 << " - " << num2 << " = " << num1 - num2 << endl; break; case '*': cout << num1 << " * " << num2 << " = " << num1 * num2 << endl; break; case '/': if (num2 != 0) cout << num1 << " / " << num2 << " = " << num1 / num2 << endl; else cout << "Error! Division by zero." << endl; break; default: cout << "Error! Operator is not correct." << endl; break; } return 0; } |
Example Outputs:
Example Output #1
Enter operator (+, -, *, /): +
Enter two numbers: 5 3
5 + 3 = 8
Example Output #2
Enter operator (+, -, *, /): –
Enter two numbers: 10 4
10 – 4 = 6
Example Output #3
Enter operator (+, -, *, /): *
Enter two numbers: 7 6
7 * 6 = 42
Example Output #4
Enter operator (+, -, *, /): /
Enter two numbers: 8 2
8 / 2 = 4
Example Output #5
Enter operator (+, -, *, /): /
Enter two numbers: 5 0
Error! Division by zero.
Example Output #6
Enter operator (+, -, *, /): &
Enter two numbers: 4 2
Error! Operator is not correct.
Memory Consumption for each variable
Variable Name | Data Type | Description | Memory Consumption |
op | char | Operator | 1 byte |
num1 | double | Operand 1 | 8 bytes |
num2 | double | Operand 2 | 8 bytes |