In: Computer Science
Question #14. a. TRUE OR FALSE: Code written using a case/switch construct can always be rewritten using an if/else construct. Explain why or why not. b. TRUE OR FALSE: Code written using an if/else construct can always be rewritten using a case/switch construct. Explain why or why not.
matlab
Question a:
Code written using a case/switch construct can always be rewritten using an if/esle construct.
Because in switch case, a variable value is checked with different cases which can also be achieved using if-elseif-else construct.
Eg:
switch(value){
case 1: //statements
case 2: //statements
case 3: //statements
default: //statements
}
The above switch statement code can be rewritten as
if(value==1)
{//statements}
else if(value==2)
{//statements}
else if(value==3)
{//statements}
else
{//statements}
Question b:
Code written using an if/else construct cannot always be rewritten using a case/switch construct.
It can be rewritten in the vice versa case of above explanation i.e.,condition checking is done on a single variable.
But in the case of conditions using multiple variables in different cases in if/else construct cannot be rewritten in switch/case construct.
Eg:
if(value==1)
{//statements}
else if(grade=='A')
{//statements}
else if(value==5)
{//statements}
else
{//statements}
The above if/else construct cannot be rewritten using switch/case construct.