A hardware merchant sells steel bars at a flat rate of Kes 1000.00 per meter, and has announced the following discounts:

Quantity of steel bar bought (per meter) Discount (%)

<20 0
21-40 5
41-60 10
61-80 15
81-100 20

100 25
Implement the following programs:

a) Using if..else statement, write a program that accepts the quantities of steel bar purchased and displays the amount to be paid by the customer.

b) Using switch statement, write a program that accepts the quantities of steel bar purchased and displays the amount to be paid by the customer.

switch statements do not permit ranges, so the only way to do that would be something like this:

switch(qty)
{
   case 21: case 22: case 23: case 24: case 25:
   case 26: case 27: case 28: // etc etc through 40
       discouint = 0.05F;
       break;

   case 61: case 62: case 63: case 64: case 65:
   case 66: case 67: case 68: // etc etc through 80
       discouint = 0.10F;
       break;      
};

And that is just plain STUPID. Much easier to use if statements.

If that is the way the assignment was given, then the only real way to go about it is to first use if/else branching to put the purchase into some discrete cagetory.

Then write the switch to use the category value.

As AD put it it, this really is an inelegant way way of going about it. Added to the fact you'd need so many case labels, you cannot deal with any fractional values at all.

Perhaps your instructor should be sent to the board to write 100 times, "I will not give stupid assignments."

Hello vmane,i had asked the whole question a week ago and i was assisted on the if/else part but no one attempted the switch that's why i editted the question.Thanks

Of course, since you still have the assignment and saying it's stupid won't accomplish much, a reasonable approach would be to compress your range with a loop and table lookup:

int lookup[] = {21, 41, 61, 81};
int discount = 0;

for (int i = 0; i < sizeof lookup / sizeof *lookup; i++)
{
    if (qty < lookup[i])
    {
        break;
    }

    discount += 5;
}

switch (discount)
{
case 0:
    // Blah
    break;
case 5:
    // Blah
    break;
case 10:
    // Blah
    break;
case 15:
    // Blah
    break;
case 20:
    // Blah
    break;
}

But if you're already finding the discount with the lookup, I'd question whether a switch is even needed. It might be able to be rolled up into little more than a final price calculation and output statement.

This article has been dead for over six months. Start a new discussion instead.