write a method called secondLargest that takes an array of integers and returns the second largest element in the array
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;
}
}
Comments
Leave a comment