Finding array index number from loop

Hello,

I am trying to find out what the index number of an array for a maximum number entered by a user.

So I have a user enter 5 numbers and the For loop picks out the maximum and prints it. I've created a new variable for the index number and had it equal 'i' in the for loop. So my logic is that it would be equal to the index corresponding with the max number it found.

Problem: No matter what position I place the max number in, i is always equal to 4. Is there anyway to pull out the index number specifically?

Thank you!



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
38
39
40
41
42
43
44
#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
	const int input = 5;
	int i, max,fmax[input], index_num = 0;
	
	
	cout <<"Enter the first element number: ";
	cin >> fmax[0];
	
	max = fmax[0];
	

	for (i = 1; i < input; i++)
	{
		cout <<"Now enter array element number " << i << ": ";
		cin >> fmax[i];

		if (max < fmax[i])
			max = fmax[i];
			index_num = i;
			
	}

	
cout << "\nThe maximum value of these numbers is: " << max << endl;
cout << "\nThis is element number [" << index_num << "] in the list of numbers" << endl;
	
	system("PAUSE");
	return 0;
}








This code has misleading indentation:
1
2
3
		if (max < fmax[i])
			max = fmax[i];
			index_num = i;


It actually does this:
1
2
3
4
5
6
    if (max < fmax[i])
    {
        max = fmax[i];
    }

    index_num = i;


So you need to (a) use braces if you want the if to control more than one statement and (b) take care with indentation, you may mislead yourself (but the compiler isn't influenced either way by indentation).
Instead of

1
2
3
		if (max < fmax[i])
			max = fmax[i];
			index_num = i;


you shall write

1
2
3
4
5
		if (max < fmax[i])
		{
			max = fmax[i];
			index_num = i;
		}
Last edited on
Solved! Thanks for the quick response. Amazing how something so little can effect the entire result.

Ithwail wrote:
Amazing how something so little can effect the entire result.

That's the nature of any computer program. A single bit changed from a one to a zero (or vice versa) can be the difference between success and failure.
Topic archived. No new replies allowed.