views:

119

answers:

3

I have a piece of ada code shown below which is a simple switch case statements.Is there any better way to convert this into C.

         for I in 1..100 loop
           case I is
                when 100 =>
                    Dollars := Dollars + 1;
                when 25|50|75 =>
                    Quarters := Quarters + 1;
                when 10|20|30|40|60|70|80|90 =>
                    Dimes := Dimes + 1;
                when 5|15|35|45|55|65|85|95 =>
                    Nickles := Nickles + 1;
                when others =>
                    Pennies := Pennies + 1;
           end case;
         end loop;

Now by adding the switch and the case for each values in the case,i can do that conversion,But it seems tyo make the code too big.Is there anywa other simple and compact way.Please get back to me if the question is not clear?

+4  A: 

Try:

for(i=1;i<=100;i++) {
    if(i == 100) {
        dollars++;
    }else if(i % 25 == 0) {
        quarters ++;
    }else if(i % 10 == 0) {
        dimes ++;
    }else if(i % 5 == 0) {
        nickles ++;
    }else{
        pennies ++;
    }
}
codaddict
@unicornaddict..Thats a nice one.But is ther anyway where we could do it using switch and case statements.
maddy
@maddy: If you want a switch based answer, Marcelo Cantos has one. You just need to add a `default: pennies ++;` added.
codaddict
@unicornaddict:Thanks for your version.That should be really appreciated.
maddy
when `i == 100` it should be `dollars++` and not `dollars = 1`
smink
+2  A: 
case 100:
    ++Dollars;
    break;
case 25: case 50: case 75:
    ++Quarters;
    break;
case 10: case 20: case 30: case 40: case 60: case 70: case 80: case 90:
    ++Dimes;
    break;
// ...

Not quite as pretty, but still efficient. If performance is at a premium, you'll want to compare the efficiency of this with @unicornaddict's answer, which is cleaner than mine.

Marcelo Cantos
@Marcelo Cantos --THANK U.I guess this is what i need.Well i just want the perfect conversion without worrying about the performances etc..
maddy
This is the right answer. If I were the C person I'd still put the cases on their own lines for clarity, but this is the right formulation.
T.E.D.
+2  A: 
for (i = 1; i <= 100; i++)
{

    if (i == 100)
    {
        Dollars++;
    }
    else if (i % 25 == 0)
    {
        Quarters++;
    }
    else if (i % 10 == 0)
    {
        Dimes++;
    }
    else if (i % 5 == 0)
    {
        Nickles++;
    }
    else
    {
        Pennies++;
    }
}
evilpie
oh too slow again ;(
evilpie