DEV Community

CoderLegion
CoderLegion

Posted on β€’ Edited on β€’ Originally published at kodblems.com

1

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!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

πŸ‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Communityβ€”every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple β€œthank you” goes a long wayβ€”express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay