Group
Flow Control in C++
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 corresponding calculation.
4. Display the result of the selected operation.
5. Make sure to handle division by zero errors.
Write a program that simulates a calculator with operations like addition, subtraction, multiplication, and division.
Example C++ Exercise
Show C++ Code
#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
}
Output
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): +
Result: 15
//Or if you try division by zero:
Enter first number: 10
Enter second number: 0
Enter operation (+, -, *, /): /
Error: Division by zero is not allowed.