DEV Community

CoderLegion
CoderLegion

Posted on • Edited on • Originally published at kodblems.com

Java: Find second largest number in an array using single loop

πŸŽ‰ Before you dive into this article...

πŸš€ Check out our vibrant new community at CoderLegion.com!

πŸ’‘ Share your knowledge, connect with like-minded developers, and grow together.

πŸ‘‰ Click here to join now!

Hi there!
I have started learning java just recently and
I found a problem in a programming exercise in which I have to find the second largest number in a given array using programming. I know how to find the largest number,
but I am facing difficulty in making the logic for finding the second-largest number.

Can anybody here help me solve the problem?
Also, provide the example program so that I can understand it better. Thanks!

Solution:
Hello! The problem you have mentioned is very easy. All you need to do is,
after finding the largest number, apply another logic.

However, consider the following code snippet, which will solve your problem.

Please refer to the comments to better understand the code:

public class Main
{
public static void main(String[] args) {
int[] arr = {5,3,7,8,2,68,4,19};
int largest = 0, second_largest = 0;
for(int i = 0; i {
//this condition will keep evaluating unless i is less than the length of array or largest number is not found
if(arr[i] > largest) //if(arr[i] > 0)
{
second_largest = largest; //second_largest = 0
largest = arr[i]; //assigning the largest element of array to 'largest' variable
}
else if(arr[i] > second_largest && arr[i] != largest)//if above condition is false, this will be evaluated in order to find the second largest number
{

          second_largest = arr[i];
        }
     }
    System.out.println("Largest:" + largest + "\nSecond largest:" + second_largest);
Enter fullscreen mode Exit fullscreen mode

}
}
Output:

Largest:68

Second largest:19

I hope you found the answer you were looking for, Thanks!

Top comments (0)