First of all factor out the code for computing the level into a separate function, say get_level:
level1 = get_level(score1);
level2 = get_level(score2);
You can implement get_level in different ways.
If the number of levels is small you can use the linear search:
const int bounds[] = {30, 49, 79}; // Add more level bounds here.
int get_level(int score)
{
const size_t NUM_BOUNDS = sizeof(bounds) / sizeof(*bounds);
for (size_t i = 0; i < NUM_BOUNDS; ++i)
if (score <= bounds[i])
return i + 1;
return NUM_BOUNDS + 1;
}
Or, if you are an STL fan:
#include <algorithm>
#include <functional>
const int bounds[] = {30, 49, 79}; // Add more level bounds here.
int get_level(int score)
{
return std::find_if(bounds,
bounds + sizeof(bounds) / sizeof(*bounds),
std::bind2nd(std::greater_equal<int>(), score)) - bounds + 1;
}
If you have many levels binary search may be more appropriate:
#include <algorithm>
const int bounds[] = {30, 49, 79}; // Add more level bounds here.
int get_level(int score)
{
return std::lower_bound(bounds,
bounds + sizeof(bounds) / sizeof(*bounds), score) - bounds + 1;
}
Or if you have relatively small number of levels then use if-else chain similar to your original version:
int get_level(int score)
{
if (score <= 30)
return 1;
else if (score <= 49)
return 2;
else if (score <= 79)
return 3;
return 4;
}
Note that putting returns on separate lines can make your program easier to trace in the debugger.