Java Program to find the 2nd Maximum and 2nd Minimum from an Array.
import java.util.Scanner;
public class maxAndMin2nd
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int i, n, min1, min2=0, max1, max2=0;
int arr[]=new int[50];
System.out.print("Enter N: ");
n=sc.nextInt();
for(i=0;i<n;i++)
{
arr[i]=(int)(Math.random()*40)+10;
System.out.print(arr[i]+"\t");
}
System.out.println();
max1=min1=arr[0];
if(max1>0) max2=0;
if(min1<5000) min2=5000;
for(i=0;i<n;i++)
{
if(arr[i]>max1)
{
max2=max1;
max1=arr[i];
}
else if(arr[i]>max2 && arr[i]<max1)
{
max2=arr[i];
}
if(arr[i]<min1)
{
min2=min1;
min1=arr[i];
}
else if(arr[i]<min2 && arr[i]>min1)
{
min2=arr[i];
}
}
System.out.println("Maximum1 is :"+max1);
System.out.println("Maximum2 is :"+max2);
System.out.println("Minimum1 is :"+min1);
System.out.println("Minimum2 is :"+min2);
}
}
public class maxAndMin2nd
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int i, n, min1, min2=0, max1, max2=0;
int arr[]=new int[50];
System.out.print("Enter N: ");
n=sc.nextInt();
for(i=0;i<n;i++)
{
arr[i]=(int)(Math.random()*40)+10;
System.out.print(arr[i]+"\t");
}
System.out.println();
max1=min1=arr[0];
if(max1>0) max2=0;
if(min1<5000) min2=5000;
for(i=0;i<n;i++)
{
if(arr[i]>max1)
{
max2=max1;
max1=arr[i];
}
else if(arr[i]>max2 && arr[i]<max1)
{
max2=arr[i];
}
if(arr[i]<min1)
{
min2=min1;
min1=arr[i];
}
else if(arr[i]<min2 && arr[i]>min1)
{
min2=arr[i];
}
}
System.out.println("Maximum1 is :"+max1);
System.out.println("Maximum2 is :"+max2);
System.out.println("Minimum1 is :"+min1);
System.out.println("Minimum2 is :"+min2);
}
}
No comments
Post your comments