# Find the second largest number in the array

• 01-13-2011, 04:34 PM
Find the second largest number in the array
I have written the following code for finding the 1st largest number in the given array and please do correct me in case there is some error in the program and can any one help me in finding the 2nd largest number in the array.
The code which i have written is as follows:

public class Assignment1 {

public static void main(String args[]) {
int i;
int temp = 95;

int arr[] = {95, 20, 34, 100, 9,150};
for (i = 0; i < arr.length - 1; i++) {

if (i == 0) {
temp = arr[i];
} else if (temp < arr[i]) {

temp = arr[i];

}
}
System.out.println("Largest is :" + temp);

}
}
• 01-13-2011, 04:39 PM
user0
Hi - have you tested your code? If so, and if it works correctly, you can do a second pass through the array to find the second largest number, using some if statements like you have done.

Also, are you not allowed to sort the array?

Best,
• 01-13-2011, 04:48 PM
user0
Hi - also, looks like you are missing the last element in your loop, due to the condition arr.length - 1. I would suggest changing the for loop to :
Code:

`for(int i = 0; i < arr.length; i++)`
Secondly, why are you initializing temp to 95? I would initialize it to the lowest possible int value:
Code:

`int temp = Integer.MIN_VALUE;`
and get rid of the first if statement you have as it would just be a waste checking if i==0 each time the loop runs.

best,
• 01-13-2011, 04:48 PM
My code works .I am not able to write the code to find the second highest number.Any help or suggestions
• 01-13-2011, 05:09 PM
JosAH
Quote:

Originally Posted by radhi16
I have written the following code for finding the 1st largest number in the given array and please do correct me in case there is some error in the program and can any one help me in finding the 2nd largest number in the array.

One loop and a couple of if-statements can do the job: think of it, suppose you have two numbers: first and second representing the largest and second largest numbers so far; also suppose a current number curr. If curr is larger or equal to first, what to do? Else, if curr is larger or equal to second, what to do?

kind regards,

Jos
• 01-13-2011, 06:08 PM