Simple Calculator Simulation in C++
In this exercise, you will create a C++ program that simulates a basic calculator. The calculator will perform simple arithmetic operations such as addition, subtraction, multiplication, and division. The user will input two numbers and choose the operation they wish to perform.
Iterative Logic
1. Input Handling
The program captures two numerical values (double) and a character (char) representing the mathematical operator.
2. Switch Control
A switch statement evaluates the operator. It efficiently routes the logic to the matching case block.
3. Error Validation
Includes a specific check for division by zero and a default case to handle unrecognized operators.
Key Concepts Learned:
- Switch Statements: Using multi-way branching for cleaner code than multiple
if-else. - Arithmetic Operators: Implementing basic math functions in a real-world scenario.
- Input Validation: Protecting the program from runtime errors like division by zero.
Objective
- 1. Ask the user to input two numbers.
- 2. Prompt the user to select an operation (addition, subtraction, multiplication, or division).
- 3. Use a switch statement to handle the operations and perform the calculation.
- 4. Display the result and handle division by zero errors.
Example C++ Exercise
#include <iostream> // Include the iostream library for input and output
using namespace std; // Use the standard namespace
// Main function - the entry point of the program
int main() {
double num1, num2; // Variables to store the two numbers
char operation; // Variable to store the selected operation
// Ask the user for input
cout << "Enter first number: ";
cin >> num1; // Read the first number
cout << "Enter second number: ";
cin >> num2; // Read the second number
// Ask the user to choose an operation
cout << "Enter operation (+, -, *, /): ";
cin >> operation; // Read the chosen operation
// Switch statement to handle different operations
switch (operation) {
case '+':
cout << "Result: " << num1 + num2 << endl; // Addition
break;
case '-':
cout << "Result: " << num1 - num2 << endl; // Subtraction
break;
case '*':
cout << "Result: " << num1 * num2 << endl; // Multiplication
break;
case '/':
// Check if division by zero is attempted
if (num2 != 0) {
cout << "Result: " << num1 / num2 << endl; // Division
} else {
cout << "Error: Division by zero is not allowed." << endl; // Handle division by zero
}
break;
default:
cout << "Invalid operation." << endl; // Handle invalid operation input
}
return 0; // Return 0 to indicate that the program executed successfully
}
Console Output:
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): +
Result: 15