If and Else How to write more efficient

How would I write this code more efficiently with If and Else?

#include <iostream>
using namespace std;


int main()
{

int score; // numeric test score

cout << "Enter your score: ";
cin >> score;

if ( score >= 90 && score <= 100 )
cout << "You made an A" << endl;

if ( score >=80 && score < 90 )
cout << "You made a B" << endl;

if ( score >= 70 && score < 80 )
cout << "You made a C" << endl;

if ( score >= 60 && score < 70 )
cout << "You made a D" << endl;

if ( score >= 0 && score < 60 )
cout << "You made an F" << endl;

return 0;
}
you can try going backwards to implicitly eliminate the bands:

1
2
3
4
5
6
7
if(score < 60)
 F
else
if(score < 70)  //because of the else, you know its >= 60 here. 
 D
...
else A (no condition, it is KNOWN at this point) 


and you can rewrite the above as a switch/case (default is A, due to the KNOWN above)

the fastest possible is probably a lookup table. Fill a vector of 100 characters with 'F', then fill in the indices of 60-69 wth 'D', 70 to 79 with 'C', etc.
then the answer is just table[score].
Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
int main()
{
   int  upper[] = {  60,  70,  80,  90, 101 };
   char grade[] = { 'F', 'D', 'C', 'B', 'A' };
   int mark, i = -1;
   cout << "Input mark: ";   cin >> mark;
   while ( mark >= upper[++i] );
   cout << "Grade: " << grade[i];
}
This is not a "with If and Else" solution:
1
2
3
4
5
6
int convert2clamp( int mark ) {
   int index = (mark-50) / 10;
   if ( index < 0 ) return 0;
   else if ( 4 < index ) return 4;
   else return index;
}
Topic archived. No new replies allowed.