Enter two numbers and an operator (+, -, *, /)

Write a C++ program that asks the user to enter two numbers and an operator (+, -, *, /).
Use a switch statement to perform the requested operation and display the result.

Enter two numbers and an operator

C++ Code for the above program is given below:

C++ code to Enter Two Numbers and an Operator

include

int main() {
double num1, num2, result;
char operation;

// Get user input
std::cout << "Enter first number: ";
std::cin >> num1;

std::cout << "Enter second number: ";
std::cin >> num2;

std::cout << "Enter operation (+, -, *, /): ";
std::cin >> operation;

// Perform operation using switch statement
switch (operation) {
    case '+':
        result = num1 + num2;
        break;
    case '-':
        result = num1 - num2;
        break;
    case '*':
        result = num1 * num2;
        break;
    case '/':
        if (num2 != 0) {
            result = num1 / num2;
        } else {
            std::cerr << "Error: Cannot divide by zero.\n";
            return 1; // Exit program with an error code
        }
        break;
    default:
        std::cerr << "Error: Invalid operation.\n";
        return 1; // Exit program with an error code
}

// Display the result
std::cout << "Result: " << result << std::endl;

return 0;

}

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top