Write a Java program to find Largest Element in an array.

Write a program to read an int array of odd length, compare the first, middle and the last elements in the array and return the largest. If there is only one element in the array return the same element.

Assume maximum length of the array is 20.

Input and Output Format:

Input consists of n+1 integers. The first integer input corresponds to n, the number of elements in the array. The next ‘n’ integers correspond to the elements in the array.

The output consists of a single Integer.

Refer sample output for formatting specifications.

Sample Input 1:

5

2

3

8

4

5

Sample Output 1:

8

Find Largest Element in the array in Java.

import java.util.*;
public class Main {
  static int n =0;
public static void main(String[] args)  {
  Scanner sc = new Scanner(System.in);
  n = sc.nextInt();
  int a[] = new int[20];
  for(int i=0;i<n;i++){
    a[i] = sc.nextInt();
  }
int n1 = display(a);
System.out.println(n1);
}
public static int display(int []a)

{
                int max=0;
                int x,y,z;
                x=a[0];
               
                y=a[n/2];
                z=a[n-1];
               
                if(x>y&&x>z)
                                max=x;
                else if(y>x&&y>z)
                                max=y;
                else if(z>x&&z>y)
                                max=z;
                return max;
}

}

Add a Comment

Your email address will not be published. Required fields are marked *

fourteen − eleven =