java program to find largest two numbers in the given array

One procedure is

import java.util.*;
public class Largest {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int i;
int a[]=new int[n];
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
Arrays.sort(a);//arrays are arranged in ascending order

System.out.println("largest number is"+a[i-1]);
System.out.println("second largest number is"+a[i-2]);
}

}
i/p: 6
5 4 9 2 7 25
o/p: largest number is25
second largest number is9

Another way is

import java.util.*;
public class Largest {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int i,temp;
int a[]=new int[n];
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
//sort operation in descending order
for(i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("largest number is"+a[0]);
System.out.println("second largest number is"+a[1]);
}

}


















No comments:

Post a Comment