C++ Code For Calculator
C++ Code For Calculator
Below is a simple C++ code for a basic calculator that can perform
addition, subtraction, multiplication, and division:
cpp
Copy code
#include <iostream>
void displayMenu() {
cout << "Simple Calculator" << endl;
cout << "1. Addition" << endl;
cout << "2. Subtraction" << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division" << endl;
cout << "5. Exit" << endl;
}
int main() {
int choice;
double num1, num2;
while (true) {
displayMenu();
cout << "Enter your choice: ";
cin >> choice;
if (choice == 5) {
cout << "Exiting..." << endl;
break;
}
switch (choice) {
case 1:
cout << "Result: " << num1 + num2 << endl;
break;
case 2:
cout << "Result: " << num1 - num2 << endl;
break;
case 3:
cout << "Result: " << num1 * num2 << endl;
break;
case 4:
if (num2 != 0) {
cout << "Result: " << num1 / num2 << endl;
} else {
cout << "Error: Division by zero!" << endl;
}
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
return 0;
}
How It Works:
1. Menu Display: The program displays a menu for the user to choose an
operation.
2. User Input: It prompts the user to enter two numbers and select an
operation.
3. Operations: Based on the user's choice, it performs the selected
arithmetic operation.
4. Error Handling: It checks for division by zero and provides appropriate
messages.
5. Exit Option: The program continues until the user chooses to exit.
You can compile and run this code in any C++ development environment. Let me
know if you need any modifications or additional features!
4o mini