Hello! Been bouncing around the forum a little bit and using it in conjunction with a book to learn C++. Coming over from VB .Net, its not too terribly difficult, and quite enjoyable!
I wanted to know if there was a better way to accomplish this, than what I've implemented here with the ifelse statements? The program was written in response to this thread:
There's nothing wrong with the solution you have there, you can't use a switch statement with a range of values. All you could really do to improve on this would be to improve the worst case, but this is a simple task so you wouldn't really gain anything, performance limitations won't start to apply until you're doing something much more complicated than this.
What I mean by improving the worst case is that in your current solution if the score is below 60 then you have to check 4 'if' statements before reaching the final 'else' which applies to that case. Assuming the the grade is a random number between 0 and 100 (which wouldn't be true of a set of exam results, but lets ignore that) then 60% of the grades would be 60 or below, yet you're using 4 if statements to establish that the grade is in that dominant range. If your first if statement checked whether the grade was below 50, and that evaluated to true, then you cut the amount of comparisons down from 4 to 1. If that result was not true, then you cut down the possible range of values down from 100 to 50, whereas your first if statement currently only cuts down the range of possible values by 10 if it evaluates to false.
Upon reflection, I don't know why I typed this much when you didn't require anywhere near such a detailed answer, but its important than you start to think like a programmer early on. If you can eliminate up to half of the possible range of values with each if statement rather than just reducing it by 10 then the worst case will be much better. Basically though, what you have there is fine.
switch(grade / 10)
{
case 10:
case 9:
cout << "You got an A!\n" ;
break ;
case 8:
cout << "You got a B!\n" ;
break ;
case 7:
cout << "You got a C!\n" ;
break ;
case 6:
cout << "You got a D!\n" ;
break ;
default:
cout << "You got an F!\n" ;
}
Alternatively you could've done:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
grade /=10 ;
if ( grade < 5 ) // map all f scores to one value
grade = 5 ;
grade -= 5; // f is 0, d is 1, c is 2, b is 3...
charconst * you_got[] =
{
"You got an F!\n",
"You got a D!\n",
"You got a C!\n",
"You got a B!\n",
"You got an A!\n",
"Your score was perfect! You got an A!\n"
};
cout << you_got[grade] << '\n' ;