I’m trying to print the largest and smallest values on an array, as well as their respective subscripts. I’m running into a problem where my code, though printing the highest and lowest values of the array, is returning the largest subscript (regardless of value) for both maximum and minimum arrays. The problem lies somewhere in the for loops, below.
int max = arrayOfNumbers[0];
int min = arrayOfNumbers[0];
int indexMax = 0;
int indexMin = 0;
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (max < arrayOfNumbers[i])
max = arrayOfNumbers[i];
indexMax = i;
}
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (min > arrayOfNumbers[i])
min = arrayOfNumbers[i];
indexMin = i;
This should work:
You forgot to put both lines after the
ifs into braces. Each time the code inside the loops executed, the current index had been written into bothindexMaxandindexMin, and that’s why after the loops finished, they contained the “largest subscript”.