Answer to Question #265312 in C++ for Usama

Question #265312

Write a program in C++ that implements a simple arithmetic calculator using enumerator. Create 

Operation enumerator with the elements (Add, Sub, Mul, Div). The function Calculate receives two 

integer numbers and operation and returns the answer.


1
Expert's answer
2021-11-13T02:01:35-0500
#include <iostream>

enum Operation {Add, Sub, Mul, Div};

int Calculator(int num1, int num2, Operation operation) {
    switch (operation) {
        case Add:
            return num1 + num2;
        case Sub:
            return num1 - num2;
        case Mul:
            return num1 * num2;
        case Div:
            if (num2 == 0) return -1;
            return num1 / num2;
    }
}

// driver for testing
int main() {
    int num1, num2;
    std::cout << "Enter 2 numbers: ";
    std::cin >> num1 >> num2;

    int op;
    std::cout << "Enter operation (1 - Add, 2 - Sub, 3 - Mul, 4 - Div): ";
    std::cin >> op;

    Operation operation;
    if (op == 1) operation = Add;
    else if (op == 2) operation = Sub;
    else if (op == 3) operation = Mul;
    else if (op == 4) operation = Div;
    else {
        std::cout << "Incorrect operation";
        return 0;
    }

    int answer = Calculator(num1, num2, operation);
    std::cout << "Answer = " << answer;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS