229k views
4 votes
Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. For division, if the denominator is zero, output an appropriate message. Limit the supported operations to -/ *and write an error message if the operator is not one of the supported operations. Here is some example output:3 4

User Noonand
by
5.7k points

1 Answer

6 votes

Answer:

The cpp calculator program is as follows.

#include <iostream>

using namespace std;

int main()

{

//variables to hold two numbers and operation

int num1;

int num2;

char op;

char operations[] = {'-', '/', '*'};

std::cout << "Enter first number: ";

cin>>num1;

std::cout << "Enter second number: ";

cin>>num2;

do

{

std::cout << "Enter the operation to be performed(-, /, *): ";

cin>>op;

if(op!=operations[0] && op!=operations[1] && op!=operations[2])

std::cout << "Invalid operator." << std::endl;

}while(op!=operations[0] && op!=operations[1] && op!=operations[2]);

std::cout<< "Numbers are "<< num1 <<" and "<< num2 <<std::endl;

std::cout << "Operator is " <<op<< std::endl;

if(op==operations[0])

std::cout << "Result is "<< num1-num2 << std::endl;

if(op==operations[1])

if(num2==0)

std::cout << "Denominator is zero. Division cannot be performed." << std::endl;

else

std::cout << "Result is "<< num1/num2 << std::endl;

if(op==operations[2])

std::cout << "Result is "<< num1*num2 << std::endl;

return 0;

}

OUTPUT

Enter first number: 12 Enter second number: 0 Enter the operation to be performed(-, /, *): + Invalid operator. Enter the operation to be performed(-, /, *): / Numbers are 12 and 0 Operator is / Denominator is zero. Division cannot be performed.

Step-by-step explanation:

1. Declare two integer variables to hold the numbers.

int num1;

int num2;

2. Declare one character variable to hold the operation to be performed.

char op;

3. Declare one character array to hold all the operations.

char operations[] = {'-', '/', '*'};

4. User input is taken for the two numbers followed by the operation to be performed.

5. Validation is applied for incorrect operation entered by the user. This is done using if statement inside a do-while loop.

6. Once the correct input is obtained, the calculator program performs the required operation on the numbers. This is done using if statements.

7. If the denominator number is zero for division operation, a message is displayed to the user.

8. The numbers followed by the operation chosen by the user are displayed.

9. The result of the operation is computed and displayed.

User Mijago
by
5.1k points