user1093111
user1093111

Reputation: 1111

Adding numbers Conditionally

This seems basic but I need to add numbers whether or not they are the condition is "on" (i'll probably change this to boolean). So my question is how to do this in C code if it is possible. I tried something of this sort and various renditions:

    dfTotalTaxOwed[nIndex] = dfFedTaxOwed[nIndex]   + if(arrNYStateTaxStatus[nIndex] == 1){dfNYStateTaxOwed[nIndex];}
                                                + if(arrNDStateTaxStatus[nIndex] == 1){dfNDStateTaxOwed[nIndex];}
                                                + if(arrNHStateTaxStatus[nIndex] == 1){dfNHStateTaxOwed[nIndex];}
                                                + if(arrOHStateTaxStatus[nIndex] == 1){dfOHStateTaxOwed[nIndex];}
                                                + if(arrPAStateTaxStatus[nIndex] == 1){dfPAStateTaxOwed[nIndex];}
                                                + if(arrNJStateTaxStatus[nIndex] == 1){dfNJStateTaxOwed[nIndex];}
                                                + dfFicaTaxOwed[nIndex];    

thanks

Upvotes: 0

Views: 86

Answers (2)

Kevin
Kevin

Reputation: 186

C control statements don't have return values so this approach won't work. Is there a reason you don't want to do a series of if statements like

if(arrNYStateTaxStatus[nIndex] == 1) {
    dfTotalTaxOwed[nIndex] += dfNYStateTaxOwed[nIndex];
}

?

Upvotes: 0

tangrs
tangrs

Reputation: 9940

You can use the ternary operator.

expr ? true value : false value

I.e. replace if(arrNYStateTaxStatus[nIndex] == 1){dfNYStateTaxOwed[nIndex];} with (arrNYStateTaxStatus[nIndex] == 1) ? dfNYStateTaxOwed[nIndex] : 0.

On a side note, you might want to consider redesigning your program to use a dictionary instead of having an array for each state.

Upvotes: 1

Related Questions