Here is a Java program to find the third largest number in an array using a loop:
Code snippet
import java.util.*;
public class ThirdLargestInArray {
public static void main(String[] args) {
// Create an array
int[] arr = {12, 13, 1, 10, 34, 11};
// Initialize the three largest elements as minus infinite
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
int third = Integer.MIN_VALUE;
// Iterate through the array
for (int i = 0; i < arr.length; i++) {
// If the current element is greater than the first largest element
if (arr[i] > first) {
// Update the third largest element
third = second;
// Update the second largest element
second = first;
// Update the first largest element
first = arr[i];
} else if (arr[i] > second && arr[i] != first) {
// Update the third largest element
third = second;
// Update the second largest element
second = arr[i];
} else if (arr[i] > third && arr[i] != second) {
// Update the third largest element
third = arr[i];
}
}
// Print the third largest element
System.out.println("The third largest element is " + third);
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Here is a Java program to find the third largest number in an array using a loop:
Code snippet
This program will print the following output:
Code snippet
If we put index in negative value then throw an exception “Index Not Found”, like -1, -0, -2
If you put position value higher than length of array then throw an exception “Index Not Found” .
Output is →
9
7
8
This is the simple C# program to find the third largest number from a given integer array.