In: Computer Science
Question: Rewrite the program in C which computes the tax due based on a tax table. Instead of using the if/else structure, use the switch statement. /* Pre : salary is predefined *Post: Returns the tax due for 0.0 <= salary <= 150,000.00; returns -1.0 if salary is outside of table range. */
double comp_tax(double salary)
{
double tax;
if (salary < 0.0)
tax = -1.0;
else if (salary < 15000.00)
tax = 0.15 * salary;
else if (salary < 30000.00)
tax = (salary - 15000.00) * 0.18 + 2250.00 ;
else if (salary < 50000.00)
tax = (salary - 30000.00) * 0.22 + 5400.00;
else if (salary < 80000.00)
tax = (salary - 50000.00) * 0.27 + 11000.00;
else if (salary < 150000.00)
tax = (salary - 80000.00) * 0.33 +21600.00;
else
tax = -1.0; return (tax);
}
Used switch statement for each condition exists to calculate tax due based on given table.
(Note that we cannot use single switch statement to calculate result for all conditions , as cases in switch statement needed to be of exact value we cannot use comparison for each cases)
That's why used switch statement for each condition to calculate tax and use condition to calculate tax as expression for switch statement if this expression is true then it will go to case:true else it will hit default case which is empty means controll gets out of switch statement and check result from other switch statement.
double comp_tax(double salary)
{
double tax;
//when salary is out of range we make value of tax = -1
switch (salary < 0.0 || salary > 150000.00) //condition for switch statement
{
case true: //if condition is true then tax becomes -1
tax = -1.0;
break;
default:
break;
}
//when salary is less then 15000.00
switch (salary < 15000.00 && salary >= 0.0)
{
case true:
tax = 0.15 * salary;
break;
default:
break;
}
//when salary is less then 30000.00
switch (salary < 30000.00 && salary >= 15000.00)
{
case true:
tax = (salary - 15000.00) * 0.18 + 2250.00;
break;
default:
break;
}
//when salary is less then 50000.00
switch (salary < 50000.00 && salary >= 30000.00)
{
case true:
tax = (salary - 30000.00) * 0.22 + 5400.00;
break;
default:
break;
}
//when salary is less then 80000.00
switch (salary < 80000.00 && salary >= 50000.00)
{
case true:
tax = (salary - 50000.00) * 0.27 + 11000.00;
break;
default:
break;
}
//when salary is less then 150000.00
switch (salary <= 150000.00 && salary >= 80000.00)
{
case true:
tax = (salary - 80000.00) * 0.33 + 21600.00;
break;
default:
break;
}
return (tax);
}
OUTPUT :