Answer to Question #184705 in Java | JSP | JSF for salma wael

Question #184705

write a method called secondLargest that takes an array of integers and returns the second largest element in the array


1
Expert's answer
2021-04-24T11:19:38-0400
public class HelloWorld {
    public static void main(String[] args) {
        int integerArray[]={5,-1,4,5,65,5,65,6,9,42,6,3};
        int secondLargestNumber=secondLargest(integerArray);
        System.out.println("The second largest element in the array is: "+secondLargestNumber);
        
    }
    /*a method called secondLargest that takes an array 
    of integers and returns the second largest element in the array*/
    private static int secondLargest(int integerArray[]){
       int largest;
       int second;
       if(integerArray[0]<integerArray[1]){ 
            largest = integerArray[1];
            second = integerArray[0];
       }else{ 
            largest = integerArray[0];
            second = integerArray[1];
      }
      for (int i = 2; i< integerArray.length ; i ++) {
        if (integerArray[i] > largest) {
           second = largest;
           largest = integerArray[i];
        }else if (integerArray[i] > second && integerArray[i] != largest) {
          second = integerArray[i];
        }
      }
      return second;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog