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

How would I convert this switch statement into an if statement? switch(opt) { ca

ID: 3884057 • Letter: H

Question

How would I convert this switch statement into an if statement?

switch(opt)
        {
            case '+':
               cout<<"Add of two doubles is "<<add(x,y)<<endl;    
                break;
           case '-':
               cout<<"Subtract of two doubles is "<<subtract(x,y)<<endl;    
               break;

           case '*':
               cout<<"Multiply of two doubles is "<<multiply(x,y)<<endl;    
               break;
           case '/':
               cout<<"Divide of two doubles is "<<divide(x,y)<<endl;    
               break;
           default:
                cout << "Error! operator is not correct";
               break;

       }

Explanation / Answer

Considering "opt" as an string,

The switch case can be converted into an if-else statement

below is the converted statement

if(opt == "+")

{

//if opt = + below stament will be printed else it will go to the next loop

cout<<"Add of two doubles is "<<add(x,y)<<endl;

}

else if(opt == "-")

{

//if opt = - below stament will be printed else it will go to the next loop

cout<<"Subtract of two doubles is "<<subtract(x,y)<<endl;

}

else if(opt == "*")

{

//if opt = * below stament will be printed else it will go to the next loop

cout<<"Multiply of two doubles is "<<multiply(x,y)<<endl;

}

else if(opt == "/")

{

//if opt = / below stament will be printed else it will go to the next loop

cout<<"Divide of two doubles is "<<divide(x,y)<<endl;

}

else

{

// if none of the conditions are met the below line will be printed by default

cout << "Error! operator is not correct";

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote