Basic Arithmetic Functions

Basic Arithmetic Functions

Create four distinct functions to perform the arithmetic operations:

Ensure that the divisor isn't zero when dividing. If an attempt to divide by zero is made, alert the user and return 0.

Each function should ask the user for two double inputs and return the result.

Prompt the user about the operation and use a switch statement to use the appropriate function in the main() function.

Answer

#include <iostream>

double addition() 
{
    double a, b;
    std::cout << "Enter two numbers for addition (separated by space): ";
    std::cin >> a >> b;
    return a + b;
}

double subtraction()
{
    double a, b;
    std::cout << "Enter two numbers for subtraction (separated by space): ";
    std::cin >> a >> b;
    return a - b;
}

double multiplication()
{
    double a, b;
    std::cout << "Enter two numbers for multiplication (separated by space): ";
    std::cin >> a >> b;
    return a * b;
}

double division()
{
    double a, b;
    std::cout << "Enter two numbers for division (separated by space): ";
    std::cin >> a >> b;

    if (b == 0)
    {
        std::cout << "Division by zero is not allowed. Returning 0.\n";
        return 0;
    }
    return a / b;
}

int main() 
{
    std::cout << "Select an operation:\n";
    std::cout << "1. Addition\n";
    std::cout << "2. Subtraction\n";
    std::cout << "3. Multiplication\n";
    std::cout << "4. Division\n";
    int choice;
    std::cin >> choice;

    switch (choice)
    {
        case 1:
            std::cout << "Result: " << addition() << "\n";
            break;
        case 2:
            std::cout << "Result: " << subtraction() << "\n";
            break;
        case 3:
            std::cout << "Result: " << multiplication() << "\n";
            break;
        case 4:
            std::cout << "Result: " << division() << "\n";
            break;
        default:
            std::cout << "Invalid choice.\n";
            break;
    }
}
Questions