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";
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.