Varun
Varun

Reputation: 91

Converting if-else to for loop

int max_range = 100;
// I do not want to add more else if.. Actually max range is still 100 with more else ifs.
// Range can take values from 0 to 100

if (range <= 10){
    a[0]= value;
}

else if (range > 10 && range <= 20){
    a[1]= value;
}

else if (range> 20 && range <= 30){
    a[2]= value;
}

else if (range > 30 && range <= 40){
    a[3]= value;
}

else if (range> 40 && <= max_range){
    a[4]= value;
}

It is simple code. I would like it to remove the nested else if's and use a for loop. How can I convert this into a for loop?

Upvotes: 0

Views: 166

Answers (3)

user3608271
user3608271

Reputation:

I would like it to remove the nested else if's and use a for loop Probably incorrect expression: There's no nested if-else in your example.

  • Loops, if-else and switch work differently however they all handle conditions:

Loops do iteration; Checking for some condition n times whereas if, switch they check once. So you cannot convert a if-else into a loop.

  • It's really a good programming trying to make the code effective and as smaller as possible but it is not always the case. If so why such experts build a huge programs with maybe millions of code lines.

  • Your code works fine.

Upvotes: 0

Caleth
Caleth

Reputation: 62576

My other answer is very particular to the boundaries being multiples of 10. A runtime modifiable version would be something like

std::set<int> boundaries = { 10, 20, 30, 40, max_range };

// ... potentially modify `a` and `boundaries`, keeping the number of elements equal

a[std::distance(boundaries.begin(), boundaries.lower_bound(range))] = value

Upvotes: 0

Caleth
Caleth

Reputation: 62576

You don't need a loop, you are doing one action.

a[std::max(0, std::min(4, (range - 1) / 10))] = value;

Upvotes: 8

Related Questions