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?
#include "stdafx.h"
#include <iostream>
usingnamespace std;
int main()
{
constint 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;
}
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).
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.