I need help rewriting my if-else statements into a switch statement,

``````//equations for final grade
LGT=(LG1+LG2+LG3+LG4)/40.*.40*100;
MTPG=MTP*.4;
MTEG=(MTE/55.)*.20*100;

sum=LGT+MTPG+MTEG;
if(sum>95)  //if-else statements, determines final grade
letter='A';
else if(sum>85)
letter='B';
else if(sum>75)
letter='C';
else if(sum>65)
letter='D';
else
letter='F';

also i need to somehow get my switch statement to notify the user with the following two cases: If their mid-term Grade is a “D”, ‘You are in danger of failing this course. Please see the Professor’ If their mid-term Grade is a “F”, ‘You are in failing this course. Your Advisor has been notified. Please see both your advisor and the Professor’

## All 7 Replies

I really don't think what you want here is a switch, it would make sense in the ruby language, but C/C++ switch statements only accept constants:

``````switch( sum ) {
case 100:
case 99:
// ... // yes you have to write them all
case 96:
letter='A';
break;
case 95:
...
case 86:
//
break;
default:
letter='F';
break;
}``````

The switch can cascade (note that I didn't break unless I reached a letter), but I think you'll actually get a slower speed than the simple boolean evaluation you are doing.

Good luck!

Edit: I changed my mind.
This switch statement will be faster than your code.
The reason is because a switch uses the constant as an offset to function pointer (linear access time), so no evaluation is done.
I think for any if-else chain of 3 length or greater, a switch will be faster if a switch is possible. (in C/C++ at least)
If that's questionable you'll have to look up the optimization in your native compiler, I have no intention of doing so. Feel free to correct me if you do this and I was wrong though!

commented: Great help +1

So.. you can't write a switch for the grade D & F alongside the if-else i made? would that be easier?

I just did it for you, what do you mean?

I said the switch would be faster even if it encompassed every case.

letter='F' should be the default case, mind you.

This is what i mean would this work after my if-else chain?

``````switch(letter)
{
case 'D':
cout<<"You are in danger of failing this course. Please see the Professor\n";
break;
case 'F':
break;
}``````

Yes.

okkay yeah I tried it out and it works :) i got another question for ya,
How do use the pow function with variables? i.e.

``````//equations for problem 9 page 99 part b
cT=(hT)/2;
iT=(base*(hT*hT*hT))/12;
LT=(sT*iT)/(8*cT);``````

how would i raise "hT" to the 3 power?

pow(base,exp);
pow((double)hT,3); // 3rd power

Be a part of the DaniWeb community

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