Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this if-else statement be made cleaner

Tags:

c++

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.

like image 338
B Smith Avatar asked Oct 25 '10 12:10

B Smith


People also ask

How do I clean my nested IF statement?

To eliminate a nested conditional statement, you can use a guard clause. A guard clause is a condition within the if statement that must be met for code execution to continue. If the condition isn't met, then no further processing is done. The guard clause favors an early return from the method.

How do I get rid of if-else condition?

To remove the If-else condition, its important to move the condition and its corresponding action to a separate construct which will be an enum. Now we start by creating a new Enum class, say- AlgorithmExecutor. java. Then for each IF scenario we add individual values in enum with match() and execute() methods.

What is if-else if used for?

The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.


2 Answers

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.

like image 93
The Archetypal Paul Avatar answered Sep 20 '22 06:09

The Archetypal Paul


Create a function where you pass in the score and it returns the level. Also, if there are going to be a lot of them you should create an array of scores and levels.

for (x=0;x < num_scores;x++)
{
   level[x] = get_level(score[x]);
}

something like that.

like image 39
phkahler Avatar answered Sep 20 '22 06:09

phkahler