Java in Program to Find the Largest Number in an Array in Java

In this program, you'll learn to Program to Find the Largest Number in an Array. This is checked using a if else statement.

Assign the first (or any) array element to the variable that will hold the maximum value Loop through the remaining array elements, starting at the second element (subscript 1). When a larger value is found, that becomes the new maximum. To make this work with object types (eg String), you will have to change the type declarations of course, but you will also have to change the comparison to use .compareTo(), which must be defined for that object type. The minimum can be found by the same algorithm, simply inverting the test. It's also easy to add a test for the minimum to this loop so that both the maximum and minimum are determined within the same loop. There is one common variation on this -- sometimes it isn't the maximum value that is desired, but the index of the maximum value (eg, so it can be changed).

Find the Largest Number in an Array


When you run the program, the output will be:

Maximum element is 89
Index of Maximum is 5

أحدث أقدم