No, you wouldn't put "else tax=0" after the if, that would just set tax(which is already 0) to 0 again unnecessarily. The way my suggestion code works is that it sets tax to 0 then looks at states it knows about, only setting the tax rate if it finds one. If it doesn't find one then tax is unchanged from the default zero.
You would place this code iin the function that calculates the tax, perhaps, or maybe make it a global, depending on the design. It depends really how many functions need access to that data. Global variables are generally considered evil because of the dependencies they create, but this would be global static data so I think the rules are probably not as strict. But get used to localisation of data, it's good practice. So for example (untested code):
Code:
double calc_tax(double price,char *state)
{
char *states[]={"GA","FL","SC"};
double taxes[]={0.06,0.04,0.05};
double tax=0.0;
for (int i=0; i<3; i++)
if (!strcmp(test_state, states[i]))
tax=taxes[i];
double total_price=price*(1.0+tax);
return total_price;
}
To extend this to more states just add the states and the tax rate to the arrays and increase the loop termination constant from 3.
Code:
char *states[]={"GA","FL","SC","UK"};
double taxes[]={0.06,0.04,0.05,0.15};
...
for (int i=0; i<4; i++) // note change from 3 to 4
...
Of course, keeping the constant in line with the arrays is tedious, perhaps you might use an array entry to indicate end of the array:
Code:
char *states[]={"GA","FL","SC","UK","X"};
double taxes[]={0.06,0.04,0.05,0.15};
...
for (int i=0; states[i][0]!='X'; i++)
...
Note the difference between "X" and 'X'. "X" is equivalent to 'X','\0' - because strings are char constants plus a terminating zero. 'X' is an integer constant and can be compared with operators like !=, but "X" cannot be compared in the same way, you must use strcmp. "X"[0]='X' so we use states[i][0]!='X' to check for the end of the array.
"X"[0] is actually a valid C expression, try printf("%c","X"[0]); and maybe some variations like printf("%c","Hello"[2]); and because of the way the square brackets work "Hello"[2] is identical to 2["Hello"] (try it! you won't break your computer, although you might confuse the hell out of people trying to read your code).
Lots for you to have a play with there :-)