This is a Java Program to Find the Second Largest & Smallest Elements in an Array.
Enter size of array and then enter all the elements of that array. Now with the help of for loop and temp variable we sort the array in ascending order. Hence we get the first and second last element as output.
Here is the source code of the Java Program to Find the Second Largest & Smallest Elements in an Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class SecondLargest_Smallest
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array(Minimum 2):");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int 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("Second Largest:"+a[n-2]);
System.out.println("Smallest:"+a[0]);
}
}
Output:
$ javac SecondLargest_Smallest.java $ java SecondLargest_Smallest Enter no. of elements you want in array(Minimum 2):8 Enter all the elements: 2 5 1 7 8 6 9 3 Second Largest:8 Smallest:1
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Practice BCA MCQs
- Apply for Java Internship
- Check Programming Books
- Check Java Books
- Apply for Computer Science Internship