Case statements

closed account (SEbf92yv)
As part of my AS level in Computing, I am currently learning about case statements. Been given some problems regarding these.
One of the questions is about matching marks to grades. So the marks go from 0 - 100, and the grades are then linking to that.
Now obviously the best method would be to use if statements, but we've been told to just use case statements. Whilst trying to do something like:

case(n<=39)
{
cout << "Your grade is a U" << endl;
}
case(n>=40 && n<=49)
{
cout << "Your grade is an E" << endl;
}

...and so on, Visual Studio can't compile it and so in order to use case statements we've had to type each individual mark out, and so this leads to 320 lines of code, and one frazzled brain, and a worn out hand.

I'm only a simple programmer at the moment, so please try to keep it simple!
Now obviously the best method would be to use if statements

Yes. This is not an appropriate use of switch. At all.

but we've been told to just use case statements

*groans*

I'm constantly flabbergasted by the poor practices and bad advise programming courses seem to give.

Anyway....

In C++, case statements can only have a single value, not a range. So the only way to do this with switch/case would be to put each individual value.


1
2
3
4
5
6
7
8
9
10
11
12
switch(n)
{

//...

case 40: case 41: case 42: case 43: case 44:
case 45: case 46: case 47: case 48: case 49:
  cout << "Your grade is an E" << endl;
  break;  // don't forget to break

//...
}


Note that you can use the default: label to catch all values that didn't have a case (you can use this for 'U' so you don't have to put cases for all 40 values).


closed account (SEbf92yv)
Ahh didn't realise they can only take one value! I think our teacher was after us to practice with case statements, but yeah that was a bit too far. Still equates to a lot of typing though!
Thanks anyway!
Topic archived. No new replies allowed.