switch statement

Hi,
how to convert the following switch statement to if-else statement

char ch;
switch(ch)
{
case 'w':cout<<"good";
case 's':cout<<"very good";
break;
case 'r':cout<<"very very good";
break;
case 'm':
case 'k':cout<<"best";
break;
default:cout<<"invalid";
break;
}
Last edited on
Logic. Think which conditions produce each output.
if the user gives 'w' what should be the output then as there is no break statement after case 'w' statement.Directly it is case 's'
That is true. Switch executes all statements between first matching case and following break. Therefore, 'w' produces "goodvery good". That should be easy to test with the switch code version.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

int x; 

cin >> x;

if (x == 'w')
{
    //do this
}
else if (x == 's')
{
   //do this
}
else if (x=='r')
{
   // do this
}
else{
    //default
}
Did this solution help you?
1
2
3
4
5
6
7
char ch;
      if(ch=='w'){cout<<"good";
}else if(ch=='s'){cout<<"very good";
}else if (ch=='r'){cout<<"very very good";
}else if (ch=='m'){ ///say something
}else if (ch=='k'){cout<<"best";
}else cout<<"invalid"; 
Last edited on
Topic archived. No new replies allowed.