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.

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.

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

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.

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.