How can I make it so that if the quantityPurchased is greater than or equal to 200 it does not go out of the bounds of array without using an if, if else, else or a switch statement.
static double DeterminePercentage(int quantityPurchased)
{
double[] quantity = { 1, 11, 50, 100, 200 };
double[] discount = { 0, 7.5, 15, 17.5, 20 };
int x = 0;
for (int i = 0; i < quantity.Length; i++)
{
if (quantityPurchased >= quantity[i] && quantityPurchased < quantity[i + 1])
{
x = i;
}
break;
}
return discount[x];
}
Just loop one item less:
To have the code work for >200 value you can add another dummy item:
This will have quantity between 200 and Int32.MaxValue have discount of 20%.