0

Hi,

If I were to write a program as follow:

if (x>90)
   cout<<"Excellent"<<endl;
else if (x>80)
   cout<<"good"<<endl;
else if (x>50)
   cout<<"average"<<endl;
else
   cout<<"bad"<<endl;

And i want to convert it to using switch case, how should i do it? I know how to use switch for constants like 1,2 and characters but I am not sure how to use it incorporating the '>' and '<' sign in. Thank you.

4
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by abhimanipal
0

you can't use > or < in switch cases -- switch can only be used with constants. In the case you posted the if statements are the best way to handle it. I suppose you could write a switch statement with 100 cases, but that would be dumb.

0

unfortunately, my lecturer's question was to do it in switch. Afraid that he'll do that for exams, so looking for answers.

0

Well, I gave you one solution -- a switch with 100 case statements. There is no alternative. But I suspect that kind of problem is not what your instructor has in mind.

Edited by Ancient Dragon: n/a

0

good news is that if you have to write it in a switch statement you can use the drop through method eg

switch (score)
case 99:
case 98:
// so on
case 90:
       //display info
       break;
case 89:
case 88:
// so on
case 80:
       //display info
       break;
case 79:
case 78:
// unfortunatly this will have to go to 50
case 50:
       //display info
       break;
default:
       // display info
}

its still a lot of writing but at least you wont have to write code for each case.

2

You could use the division operator to convert marks from 1-100 range to 1-10. Then you just have to write 10 switch cases

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.