Largest element in an array using java

The largest element in an array using java

 

Here we will discuss, how to find the largest element in the array using java.

To find the largest number in the array, we need to compare every element in the array with every element.

Here we perform compression so here, we need to store the first index value in the temporary variable and then compare it with every other element. for each iteration of comparison, we need to store the present index value in the temporary variable.

larger

Working

Step 1. Initialize an array.

Step 2. Declare the scanner class for taking input.

Step 3. take array size from the user.

Step 4. Take element of array from the user.

Step 5. Print smaller value from calling smaller function.

Step 6. Print larger value from calling larger function.

Larger(int a[],int size)

Step 1. Store first element of array in the large variable.

Step 2. Initialize the loop from 0 to size of the array.

Step 3. Compare the all element to the large variable. if the number is greater than the larger variable so store it in the large.

Step 4. Return large.

Java program to find the largest number in the array

import java.util.Scanner;
public class Main
{
public static int larger(int[] arr,int size)
{
int large=arr[0];
for(int i=0;i<size;i++)
{
if(arr[i]>large)
large=arr[i];
}
return large;
}
public static void main(String[] args)
{
int[] a = new int[50];
Scanner sc=new Scanner(System.in);
System.out.print("enter size ");
int size=sc.nextInt();
System.out.println("enter Element");
for(int i=0;i<size;i++)
a[i]=sc.nextInt();
System.out.println("largest: "+larger(a,size));
}
}

Output

enter size 5
enter Element
23
12
15
5
32
largest: 32

Please Login/Signup to comment