Loop to calculate tax

There are certain tax ranges, for example, 0 - 10,000 gets taxed at 20%, 10,000-20,000 gets taxed at 25%, etc. So if your income was 15,000, the first 10,000 is taxed at 20%, and the remaining 5,000 is taxed at 25%. Rather than using a bunch of if statements, (ex. if (income <= 10,000){do this} if income <=20,000 && income >= 10,000){do this})
I would like to use a for loop to calculate income tax. The tax rates and ranges are stored in arrays. I have an idea how to do it, but can't quite get it right.

1
2
3
4
5
6
7
  for (i=0; i < size_of_array; i++)
  {
    if (income <= array[i]) //if the income is less than the first element of the array, ie 10,000
   { 
    tax = rate * income 
   }
   else tax = (rate * bracket) + (income - bracket)*rate


I know how to do the calculation by hand, as I showed above, but I'm having a hard time converting the logic to c++
Maybe it's not quite what you're hoping for, but....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// note for this to work, make the first member of tax rates/brackets 0;
// if you don't want the 0 tax rate, change rate[i] to rate[i-1]
double tax=0;
for (int i=1; i<size_of_array; i++) // note that i starts at 1 to stop segmentation error
{
    if (income>= bracket[i])
    {
         tax+=rate[i] * (bracket[i] - bracket[i-1]);
    }
    else
    {
         tax+=rate[i] * (income - bracket[i-1]);
         break;
    }
}
//make sure to declare the other variables at some point 

If you don't make the first bracket element 0, the code gets a fair bit longer, since you have to make special provisions for when i=0.
Last edited on
I have wrote a c++ program similar to it but without arrays, I just used a structure to store people info, and calculated their income tax depending on the brackets they were in.
Topic archived. No new replies allowed.