Java Program to find Largest element in the array

Get array size n and n elements of array, then find the largest element among those elements.

Sample Input 1:

5 5 7 9 3 1

Sample Output 1:


Program or Solution

import java.util.*;
class LarArr
  public static void main(String args[])
     int size,i,num;
     Scanner sc=new Scanner(;
     System.out.println("Enter Size Of Array:");
     int a[]=new int[size];
     System.out.println("Enter The Array Elements:\n");

     int max=a[0];

       System.out.println("The Largest Element In The Array Is:"+max);

Program Explanation

Array is a Collection of data with same type.

1. Get the size of the Array

2. Create a array with the given size (Array has 0 to size-1 index to access every location)

        0                        1                        2                         3              ......             size-2                  size-1

3. Get Inputs for Array (See Previous Problems for detail)

4. Initially assume a[0] is the largest number

     max = a[0]

In the second For Loop,

i starts at 0, and incremented by 1 after every iteration. iteration stops when i is equal to size.

in every iteration the  if(a[i]>max) checks the located element in current index is greater than max

if the element located in any position is greater than max, then assign the element as max by using max = a[i]

finally max holds the maximum value in the array after all the iterations.