yeah, but why does that mean more power?
This is a discussion on why only the succeeding value adds up??? within the C Programming forums, part of the General Programming Boards category; yeah, but why does that mean more power?...
yeah, but why does that mean more power?
you could replace the whole switch with a small array (no more conditionals):
Code:int total[]={0/*unused*/,25,55,45,...}; printf(...) scanf("%u",&order); sum+=total[order%the_appropriate_value];
You CAN of course use if/else instead of switch/case - but consider what the compiler does if you have a value 8 for this:
Unless it figures out that it's a "switch in disguise", it will compare down the chain until it finds the one that matches. In a switch/case block, the compiler will (most of the time) generate a jump-table, which means that no matter how many variants it is, there will be a O(1) type, rather than O(n) that the if/else version does.Code:if(order==1){ total=25.00; } else if (order==2){ total=55.00; } else if(order==3){ total=45.00; } else if (order==4){ total=35.00; } else if(order==5){ total=50.00; } else if (order==6){ total=70.00; } else if(order==7){ total=80.00; } else if(order==8){ total=15.00; }
Note that reasonably modern/clever compilers, such as gcc 3.4 can not figure out that the above is a "switch/case in disguise". I just tried out the above code as a if/else, and as a switch/case, and for the average case, the code is simply shorter and better for the switch/case statement.
But if it's part of your assignment to use if-else, then do so.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.