Can this if-else statement be made cleaner

c++

Solution

This rather depends on what you mean by efficiency. You could keep the limits for each level in an array

int level_limits[] = {0, 30, 49, 79, [...]};

int getLevel(int score)
{
   int level;
   for (level = 0; level < N_LEVELS; ++level)
       if (level_limits[level] > score)
            return level;
   return level; // or whatever should happen when you exceed the score of the top level
 }
 ...

 level1 = getLevel(score1);
 level2 = getLevel(score2);

... or something like that.

Problem

I am trying to improve a C++ assignment to make it more efficient. I am a beginner with the language (and programming in general too), so I am only using what I know so far (if, else). I have a function that converts scores into levels, so anything under 30 = 1, 30-49 = 2, 50-79 = 3 and so on... Here is how I am doing it: ``` if (score1 <= 30) level1 = 1; else if (score1 <= 49) level1 = 2; else level1 = 3; if (score2 <= 30) level2 = 1; else if (score2 <= 49) level2 = 2; else level2 = 3; //etc... ``` Is there a better way to do this, as I am aware this will require a new line for every single score I have.

Original source