-
searching an array
I have a program that creates an array and prompts for ints to fill the array. Then my program determines how many ints were entered, what the min and max are and calculates the average.
Now what I need to be able to do is determine if any of the values entered are higher than the average and if so, print the index number and the value stored there.
Here is the bit of code I have so far:
Code:
for (i = 0; i < max_input; i++)
{
if (nums[input] > avg)
cout << endl << "Index " << i << " value " << nums[input] << endl;
return(0);
}
The output I am getting now is usually "Index 0 value 323546786" or some crazy number which is not even close to any of the test ints I enter.
Brian
-
Your FOR loop should use the iterator value, 'i', as the array index.
Ex.: nums[i]
Whatever 'input' is, nums[input] is being displayed, not the value that you want to test from your array. Remember that built-in arrays will let you overread and overwrite their limits which is why you're picking up total garbage with nums[input]. ;)
Try this instead:
Code:
for (i = 0; i < max_input; i++)
{
if (nums[i] > avg)
cout << endl << "Index " << i << " value " << nums[i] << endl;
return(0);
}
Also, double-check your use of 'max_input'. It should be a counter of the number of integers entered into your array. Otherwise, you may have yet another bug in this code snippet.
-Skipper
-
Also, recheck that return(0) you have. That will quit the current function you are in, so you will only loop through 1 element.
-
working now
Thanks for the help. :) :)
It is working now, I think both the return (0) and the i as iterator needed to be changed.
Brian