• Register
0 votes
399 views

Problem:

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!
10.4k points

Please log in or register to answer this question.

1 Answer

0 votes

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<arr.length; 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);
}
}

Output:

Largest:68                                                                                                                    
Second largest:19                                                                                                             
 

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

28.4k points