### 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!

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344`` ``````#include "stdafx.h" #include 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; } ``````
 ``123`` `````` if (max < fmax[i]) max = fmax[i]; index_num = i;``````

It actually does this:
 ``123456`` `````` 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).

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

you shall write

 ``12345`` `````` 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.