Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find largest number of an array .

Java Code Example — Array Programs

ADVERTISEMENT

Java Program to find largest number of an array .

Objective

Write a Java program to find the largest number in an array.

Algorithm / Approach

  1. Define a method max(int[] a).
  2. Initialize a variable max with the first element of the array (a[0]).
  3. Start a for loop from i = 0 to a.length - 1.
  4. Inside the loop, check if the current element a[i] is greater than max.
  5. If true, update max with a[i].
  6. After checking all elements, print max.
Test.java
class Test {
 void max(int[] a) {
  int max = a[0];
  for(int i = 0; i< a.length; i++) {
   if(max < a[i]) {
    max = a[i];
   }
  }
  System.out.print("Max = "+max);
 }
 public static void main(String[] a)
 {
  int[] ar = {34,23,67,45,23};
  Test t = new Test();
  t.max(ar);
 }
}

Expected Output

Max = 67

Explanation of the Program

  • This algorithm uses the "King of the Hill" approach. We assume the first element is the largest.
  • We then challenge this assumption by comparing it against every other element in the array.
  • Whenever we find an element larger than our current maximum, we dethrone the old maximum and store the new champion.
  • By the time we reach the end of the array, the variable is guaranteed to hold the absolute largest value.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT