Print larger number of an array

Asked

Viewed 4,974 times

0

I have a program where I read 3 values and store in an array, but I would like to print the highest value of this array.

Follow my code below:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    int[] grade = new int[3];

    for (int i = 0; i < 3; i++) {
        System.out.println("Insert your grade: ");
        grade[i] = input.nextInt();
    }
    System.out.println(grade[0]);
}
  • Look at this example: [2,5,7]; (5-2=3),(7-2=5) Conclusion: Every difference that is positive is greater, if negative is less, and if 0 is equal. Formula : Selected value - initial value.

  • Thanks for the help!

2 answers

4


One way to find the largest number is simply to go through the array and compare its values:

int maior = Integer.MIN_VALUE;
int indiceMaior = -1;
for (int i = 0; i < grade.length; i++) {
    if (grade[i] > maior) {
        maior = grade[i];
        indiceMaior = i;
    }
}
System.out.printf("Maior número é %d, no índice %d", maior, indiceMaior);

The maior begins with Integer.MIN_VALUE, which is the smallest value an integer can have in Java (in this case, it is -2147483648). I start with the lowest possible value, so I guarantee that, no matter what numbers I have in the array, all will be larger or equal to it.

Then I loop, and for each element of the array, I see if it is larger than maior. That means that during the loop, the variable maior contains "the largest number I have found so far". When I find a larger number, I update the value of maior, and also your respective index (since you informed in the comments who wanted the index).

Notice that in the loop I use grade.length instead of putting the number 3 explicitly. So, if the array size changes, you don’t need to update your for.

At the end of the loop, just print the values.


Details

If the largest number appears more than once in the array, the index will be that of the first one. For example, if the array is:

int[] grade = { 2, 1, 2 };

In that case, the exit will be:

Maior número é 2, no índice 0

That is, the first 2 will be considered the largest (the one in the third position - in index 2 - will be disregarded).


There’s still one Egde case, which is when the array is like this:

int[] grade = { Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE };

In this case the exit is:

Maior número é -2147483648, no índice -1

As the program never enters if (since none of the values is greater than Integer.MIN_VALUE), the index ends up being -1.

This could be solved in two ways. The first is changing the condition of if for >=:

for (int i = 0; i < grade.length; i++) {
    if (grade[i] >= maior) {
        maior = grade[i];
        indiceMaior = i;
    }
}

Only now, when there are repeated values, it considers the last occurrence. Therefore, the output is:

Maior número é -2147483648, no índice 2

And in the previous example, that array is { 2, 1, 2 }, it would also return index 2.

Another way to solve would be to start with the first element (instead of Integer.MIN_VALUE), and traverse the array from the second position:

int[] grade = { Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE };
int maior = grade[0];
int indiceMaior = 0;
for (int i = 1; i < grade.length; i++) {
    if (grade[i] > maior) {
        maior = grade[i];
        indiceMaior = i;
    }
}

Now the way out is:

Maior número é -2147483648, no índice 0

Bonus

If you just want to find the largest number of the array, regardless of the index, there are other alternatives (although I understand that probably is an exercise and the teacher wants it to be done in a loop, but anyway).

Starting with Java 8, it is possible to use the streams:

import java.util.Arrays;

int maior = Arrays.stream(grade).max().getAsInt();

Of course that in the background is a disguised loop (besides having a performance worse than a simple loop), but it’s an alternative.


Another way would be to use one java.util.List instead of an array, so it is possible to use the method Collections.max:

List<Integer> notas = new ArrayList<>();
Scanner input = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
    System.out.println("Insert your grade: ");
    notas.add(input.nextInt());
}
int maior = Collections.max(notas);

Finally, for the specific case where the array has only 3 values, nor need loop. Just use Math.max twice:

int maior = Math.max(Math.max(grade[0], grade[1]), grade[2]);
  • Java has the apply method in Math.max?

  • @Maurydeveloper Não

  • 1

    Thank you very much!

0

Just do a check using the for as follows:

int valorMaximo = grade[0];

for(int number:grade){
    if (valorMaximo < number){
        valorMaximo = number;
    }
}

To check which index is the highest number just add an auxiliary variable to store the position of the value in the for. To make it simpler, you can even replace the for each for a is normal. See how it would look:

int valorMaximo = grade[0];
int index = 0;

for(int i = 0; i < grade.length; i++){
    if (grade[i] > valorMaximo){
        valorMaximo = grade[i];
        index = i;
    }
}

This code also works for negative numbers. Look, between the number -4 and -1 Which is the biggest one for you ? When the program is checked, it will always get the value that is greater than what it has. Soon if the array is an {-3,5,-1}, the highest value you will get is the 5, because the first time the variable will have the value -3, but in the next loop it will have the value 5 for the number 5 is greater than the number -3. After that it will go for another loop, but will not get the value -1 for the number -1 is less than the value that the variable has.

After this check just print the final amount. I hope I helped you :)

  • Thank you very much, I did what you said and it worked!

  • @Pedroguilherme Missing test when the array only has negative numbers...

  • True, I would also like to know how I inform you that the most valuable this, would help me in this ??

  • yes, I’ll edit my answer ok ?

  • It worked here, thank you again!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.