Java Array find the largest element

Introduction

Use a variable named max to store the largest element.

Initially max is array[0].

To find the largest element in the array, compare each element with max, and update max if the element is greater than max.

public class Main {
  public static void main(String[] args) {
    int[] array = new int[5];

    for (int i = 0; i < array.length; i++) { 
      array[i] = (int)(Math.random() * 100); 
    } //www .  ja  v  a 2  s . c o m
    
    for (int i = 0; i < array.length; i++) { 
      System.out.print(array[i] + " "); 
    } 

    double max = array[0]; 
    for (int i = 1; i < array.length; i++) { 
       if (array[i] > max) max = array[i]; 
    } 


    System.out.println(max);
  }
}



PreviousNext

Related