Reputation: 41
I need help converting this code into a switch.
if(val >= 0 && val < 10)
cell[0].plus1();
else if(val >= 10 && val < 20 )
cell[1].plus1();
else if(val >= 20 && val < 30 )
cell[2].plus1();
else if(val >= 30 && val < 40 )
cell[3].plus1();
else if(val >= 40 && val < 50 )
cell[4].plus1();
else if(val >= 50 && val < 60 )
cell[5].plus1();
else if(val >= 60 && val < 70 )
cell[6].plus1();
else if(val >= 70 && val < 80 )
cell[7].plus1();
else if(val >= 80 && val < 90 )
cell[8].plus1();
else if(val >= 90 && val < 100 )
cell[9].plus1();
Any help will be highly appreciated.
Upvotes: 2
Views: 108
Reputation: 1616
int division = val / 10;
now val >=0 && val < 10 equals division = 0
etc...
Upvotes: 0
Reputation: 12213
Since the cases in a switch statement are determined by equality, an if-else ladder using inequality can not naturally be modelled by a switch statement.
You could list out each of the values in the range and utilize the fall-through nature:
switch (val)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
cell[0].plus1();
break;
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
cell[1].plus1();
break;
...
}
This really is not any improvement to your code and quickly becomes very unwieldy.
Since each of your conditions perform the exact same operation (cell[ X ].plus1()
), all you really need is to handle the relationship between the input val
and the array index. As Eran's answer shows, in your code this relationship is a simple matter of integer division. I recommend choosing his answer.
Upvotes: 0
Reputation: 6274
If you really want a switch
, you can do:
int v = val/10;
switch(v) {
case 1: cell[1].plus1();
break;
case 2: cell[2].plus1();
break;
case 3: cell[3].plus1();
break;
case 4: cell[4].plus1();
break;
case 5: cell[5].plus1();
break;
case 6: cell[6].plus1();
break;
case 7: cell[7].plus1();
break;
case 8: cell[8].plus1();
break;
case 9: cell[9].plus1();
break;
}
But you could simply do (which is equivalent):
if (val >= 0 && val < 100) cell[val/10].plus1();
Upvotes: 1
Reputation: 393781
You don't need a switch statement.
All these statements can be reduced to :
if (val >= 0 && val < 100)
cell[val/10].plus1();
Upvotes: 13