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

1. Change the if-else statement in to a switch statement. (10 points) // include

ID: 657955 • Letter: 1

Question

1. Change the if-else statement in to a switch statement. (10 points)

// includes all necessary headers.

// <iostream> for cin and cout. <iomanip> for setprecision(), fixed, showpoint etc.

// <cmath> for pow function.

#include<iostream>

#include<string>

#include<cmath>

#include <iomanip>

using namespace std;

// main function

int main ()

{

        // declaring variables

        double num1, num2,answer ;

        char symbol;

// Prompts user for choice of arimetic expression to use.   

cout << "Please input calculation operation eg. (1 + 2): ";

cin >> num1 >> symbol >> num2 ;

// result if addition is chosen

if(symbol=='+'){

answer = num1 + num2;

}

// result if subtraction is chosen  

else if(symbol == '-'){

answer= num1 - num2;

}

// result if multiplication is chosen

else if(symbol == '*'){

answer = num1 * num2;

}

// result if division is chosen  

else if (symbol == '/'){

answer = num1 / num2;

}

// result if modulus is chosen

else if (symbol == '%'){

answer = static_cast<double>(static_cast<int>(num1) % static_cast<int>(num2));

}

// result if exponent is chosen

else if(symbol == '^'){

answer = pow ( num1, num2);

}

// output from the arimetic expression

cout << fixed << showpoint << setprecision(2);

cout << "The answer is:" << endl;

cout << num1 << " " << symbol << " " << num2 << " = " << answer << endl;

system("pause");

return 0;

}

Explanation / Answer

// <cmath> for pow function.
#include<iostream>
#include<string>
#include<cmath>
#include <iomanip>
using namespace std;
// main function
int main ()
{
// declaring variables
double num1, num2,answer ;
char symbol;
// Prompts user for choice of arimetic expression to use.   
cout << "Please input calculation operation eg. (1 + 2): ";
cin >> num1 >> symbol >> num2 ;

switch(symbol) {
case '+': // result if addition is chosen
   answer = num1 + num2;
break;
case '-':// result if subtraction is chosen
answer= num1 - num2;
break;
case '*':// result if multiplication is chosen
answer = num1 * num2;
break;
case '/':// result if division is chosen
answer = num1 / num2;
break;
   case '%'://result if modulus is chosen
answer = static_cast<double>(static_cast<int>(num1) % static_cast<int>(num2));
break;
   case '^': result if exponent is chosen
answer = pow(num1,num2);
break;
default:
/* If operator is other than +, -, * ,/ , % or ^, error message is shown */
printf("Error! operator is not correct");
break;
}
cout << fixed << showpoint << setprecision(2);
cout << "The answer is:" << endl;
cout << num1 << " " << symbol << " " << num2 << " = " << answer << endl;
system("pause");
return 0;

}