Javakiddie
Javakiddie

Reputation: 35

Printing Index number of array

I am trying to print an output that would find the max number and also print the index number of the array as well. I am able to print the max number but I am unable to print the index number.

public static int findMax(int[] allNumbers) {
    int maxValue = allNumbers[0];
    for (int i = 1; i < allNumbers.length; i++) {
        if (allNumbers[i] > maxValue) {
            maxValue = allNumbers[i];
        }
    }
    return (int) maxValue;
}

my array:

int[] allNumbers = new int[inpNum];

I can call the max number with the following findMax(number)

Upvotes: 1

Views: 83

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56423

You can return an array of the max value and index:

public static int[] findMax(int[] allNumbers) {
        int maxValue = allNumbers[0];
        int index = 0;
        for (int i = 1; i < allNumbers.length; i++) {
            if (allNumbers[i] > maxValue) {
                maxValue = allNumbers[i];
                index = i;
            }
        }
        return new int[] {maxValue , index};
}

Upvotes: 2

Related Questions