Write a java proram to find largest and second largest element in an Array.
Write a java proram to find second largest element in an Array.
Or
Write a java proram to find largest and second largest element in an Array.
Program:
import java.util.*;
public class second_largest
{
public static void main (String args[])
{
int n,i,j;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the  size  of an array: ");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter the  elements of an array: ");
for(i=0; i<n; i++)
{
a[i]=sc.nextInt();
}
for ( i = 0; i < n; i++) 
{ 
for ( j = 0; j < n; j++)
 { 
   if (a[i] < a[j])
   { int temp = a[i]; 
   a[i] = a[j]; 
   a[j] = temp; 
   }
 }
 }
 System.out.println("Second Largest element is:"+a[n-2]); 
System.out.println("Largest element is:"+a[n-1]); 
}
}
Output:
Enter the  size  of an array: 
6
Enter the  elements of an array: 
10
5
6
7
8
12
Second Largest element is:10
Largest element is 12
OR
import java.util.*;
public class second_largest
{
public static void main (String args[])
{
int n,i,j;
int largest,secondlarge;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the  size  of an array: ");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter the  elements of an array: ");
for(i=0; i<n; i++)
{
a[i]=sc.nextInt();
}
largest=secondlarge=a[0];
for ( i = 0; i < n; i++) 
{ 		
	if (a[i] > largest) 
   { 	secondlarge = largest; 		
   		largest = a[i]; 		
	}
 else if (a[i] > secondlarge)
  { 	secondlarge = a[i]; 		
	}
	}
System.out.println("Second Largest element is:"+secondlarge); 
System.out.println(" Largest element is:"+largest); 
}
}
Output:
Enter the size of an array:
5
Enter the elements of an array:
10
5
12
15
18
Second Largest element is:15
Largest element is:18
Comments
Post a Comment