Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

// in C++ Redo using a switch for selecting mathOpeator (The outer if - else if)

ID: 3769454 • Letter: #

Question

// in C++ Redo using a switch for selecting mathOpeator (The outer if - else if) #include using namespace std; int main(){ double operand1, operand2, result; char mathOperator; bool isContinue=true; cout<<"Enter two numbers: "; cin>>operand1>>operand2; cout<<"Enter the operator: (+ - * /) "; cin>>mathOperator; if (mathOperator == '+') result = operand1 + operand2; else if (mathOperator == '-') result = operand1 - operand2; else if (mathOperator == '*') result = operand1 * operand2; else if (mathOperator == '/') { if (operand2 == 0) { cout <<"Divid by ZERO "; isContinue = false; } else result = operand1 / operand2; } else cout <<"Invalid Operator: "<

Explanation / Answer

Hi,

Below is the solution to your question:

/*Simple calculator using Switch statement*/

# include <iostream>
# include <cmath>
using namespace std;
int main()
{
char ch;
float number1,number2;
cout << "Enter operator either +, -, * or /: "<<endl;
cin >> ch;
cout << "Enter the two operands: "<<endl;
cin >> number1 >> number2;
switch(ch) {
case '+':
cout << number1+number2;
break;
case '-':
cout << number1-number2;
break;
case '*':
cout << number1*number2;
break;
case '/':
       if(number2==0)
{
cout<<"Invalid,Divide by zero is not possible !!!"<<endl;
}
cout << number1/number2;
break;
default:
/* If operator is anything other than +, -, * or /, error message is shown */
cout << "Invalid operator"<<endl;
break;
}
return 0;
}

Output:

Enter operator either +, -, * or /: -

Enter the two operands:

8

3

8 - 3 = 5

Hope that helps...HAPPY ANSWERING!!!!!!!