Different way to search an array?

I have to write a program for my class the makes to arrays on with a tax rate and another with a income. The user inputs a gross income and the program searches the income array to find out what range the users income is in and then multiplies the users gross income by the related tax rate from the tax rate array.
In my program i searched the income array as is in the program, but the way i did it i had trouble getting the last element of the array to be used properly so i added the second if block. What i would like to know is there another way to do this that is a little cleaner, but still looks kind of the same.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
int main()
{
	const int SIZE = 5;
	double Rate[SIZE] = {0.0, 0.05, 0.10, 0.15, 0.20}, GrossIncome;
	int Taxes, x, IncomeRange[SIZE] = {0, 10000, 20000, 50000, 100000};
	bool search = false;
	char exit;
	
	do
	{
	cout << "Please enter your Gross Income: ";
	cin >> GrossIncome;

		for (x = 0; x < SIZE; x++)
		{
			if (GrossIncome < IncomeRange[x])
			{
				Taxes = GrossIncome * Rate[x-1];
				cout << "Your taxes are: " << Taxes << endl;
				cout << "Would you like to enter more Income amounts? Y/N:";
				cin >> exit;
				x = 5;
			}
			if (GrossIncome >= IncomeRange[4])
			{
				Taxes = GrossIncome * Rate[4];
				cout << "Your taxes are: " << Taxes << endl;
				cout << "Would you like to enter more Income amounts? Y/N:";
				cin >> exit;
				x = 5;
			}
		}
	}
	while (exit == 'Y' | exit == 'y');
	system ("pause");
	return 0;
}

Last edited on
IMHO your method works and elegant enough, you can also have a look at vectors (http://www.cplusplus.com/reference/stl/vector/) for example

- but don't use this x=5; a simple break; statement is less baffling
- shouldn't Taxes be a double type?
- and, yeah system("pause"); shouldn't be used (yada-yada), ref: http://www.cplusplus.com/forum/beginner/1988/
Last edited on
@Line 18:
Be careful here, as you're running the risk of a segmentation fault... remember that x starts at 0 and goes to SIZE - 1, which by the way is the range of possible (valid) indexes for your entire array.

-Albatross
Last edited on
@Albatross
I don't think line 18 can hear you =)

Generally arrays don't like indexing their neighbors in front of them. They don't usually get along, and the compiler has to get involved... that's always ugly.
Topic archived. No new replies allowed.