-1

I am writing a code for Calculation of Tax according to Slabs:

Range ---- Tax Levied

2.5-5 Lakhs ---- 5%

5-10 Lakhs ---- 20%

Above 10 Lakh ---- 30%

No Tax under 2.5 Lakhs.

Code:-

#include<stdio.h>
int main()
{
    float salary, tax_amount = 0;
    printf("Enter the Salary:-");
    scanf("%f", &salary);
    while (salary > 250000)
    {
        if (salary > 250000 && salary <= 500000)
        {
            tax_amount += (salary - 250000) * 0.05;
            break;
        }
        else if (salary > 500000 && salary >= 1000000)
        {
            tax_amount += (salary - 500000) * 0.20;
            salary = 500000;
        }
        else
        {
            tax_amount += (salary - 1000000) * 0.30;
            salary = 1000000;
        }
    }
    printf("Net Tax Amount:-%.3f", tax_amount);
    return 0;
}

This code isn't giving me the desired output? Can anyone tell me the where I went wrong?

  • 1
    `if (salary > 500000 && salary >= 1000000)` should be `if (salary > 500000 && salary <= 1000000)` . Note the `<=` on the second pair of terms. – WhozCraig Jun 25 '22 at 07:18
  • 2
    This would have been a very good time to learn how to [*debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). For example using a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) you can step through the code statement by statement while monitoring variables and their values. If you do that then the problem should have been easy to spot. Or in this case, perhaps a little [*rubber duck debugging*](https://en.wikipedia.org/wiki/Rubber_duck_debugging) might have been enough. – Some programmer dude Jun 25 '22 at 07:39
  • 1
    Please try to avoid using words like *lakh* that are not understood globally, and use for example *million* or * thousand* instead – James Z Jun 27 '22 at 18:08

1 Answers1

2

I guess you've made an error in your if condition . Try the following :

    #include<stdio.h>
int main()
{
    float salary, tax_amount = 0;
    printf("Enter the Salary:-");
    scanf("%f", &salary);
    while (salary > 250000)
    {
        if (salary > 250000 && salary <= 500000)
        {
            tax_amount += (salary - 250000) * 0.05;
            break;
        }
        else if (salary > 500000 && salary <= 1000000) // Error here changing >= to <=
        {
            tax_amount += (salary - 500000) * 0.20;
            salary = 500000;
        }
        else
        {
            tax_amount += (salary - 1000000) * 0.30;
            salary = 1000000;
        }
    }
    printf("Net Tax Amount:-%.3f", tax_amount);
    return 0;
}
NewbieDeveloper
  • 408
  • 1
  • 10