In this tutorial you will learn about the Java Program to Find 3rd Largest Number in an array and its application with practical example.
In this tutorial, we will learn to create a Java Program to Find 3rd Largest Number in an array using java programming.
Prerequisites
Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Java Program to Find 3rd Largest Number in an array
In this program we will find smallest element in an array using nested for loop. We would first declared and initialized the required variables. Next, we will find smallest number in an array. Lets have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
//java program to fing 3rd largest in an array public class Third{ public static int Third_Largest(int[] a, int size){ //declaring variables in sorting array int temp; for (int i = 0; i < size; i++) //sorting array { for (int j = i + 1; j < size; j++) { if (a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } return a[size-3]; //finding third largest in an array. } public static void main(String args[]){ int a[]={1,2,5,6,3}; //initialize values.. //Printing result.. System.out.println("Third Largest in an array: "+Third_Largest(a,5)); } } |
Output
3rd Largest in an array[].
In the above program, we have first declared and initialized a set variables required in the program.
- a[]= it will hold array values
- l= it will hold length of an array.
- i and j for iteration
- temp = it will hold temporary value of an array.
After declaring variables we initiate values in an array[]
here we will call a function where we fin second greatest in an array[].
3rd Largest in an array
-
- Compare the first two elements of the array
- If the first element is greater than the second exchange them.
- Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them.
- Repeat this till the end of the array.
- and at last function return a[size-3];
- which is the second largest in an array[].
and finally we will print the result it means the second largest in an array[].