Results 1 to 6 of 6
 01132011, 04:34 PM #1Member
 Join Date
 Jan 2011
 Posts
 30
 Rep Power
 0
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);
}
}
 01132011, 04:39 PM #2Senior Member
 Join Date
 Dec 2010
 Posts
 100
 Rep Power
 0
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,user0
 01132011, 04:48 PM #3Senior Member
 Join Date
 Dec 2010
 Posts
 100
 Rep Power
 0
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 :
Java Code:for(int i = 0; i < arr.length; i++)
Java Code:int temp = Integer.MIN_VALUE;
best,user0
 01132011, 04:48 PM #4Member
 Join Date
 Jan 2011
 Posts
 30
 Rep Power
 0
My code works .I am not able to write the code to find the second highest number.Any help or suggestions
 01132011, 05:09 PM #5
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 13,881
 Blog Entries
 7
 Rep Power
 22
One loop and a couple of ifstatements 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,
Joscenosillicaphobia: the fear for an empty beer glass
 01132011, 06:08 PM #6Member
 Join Date
 Jan 2011
 Posts
 30
 Rep Power
 0
Similar Threads

Finding the largest number in an array
By starchildren3317 in forum New To JavaReplies: 14Last Post: 11032010, 07:49 AM 
Help with Binary recursive method to find the largest integer
By flyingcurry in forum New To JavaReplies: 12Last Post: 10312010, 07:14 PM 
Find max number in 2D array?
By spatel14 in forum New To JavaReplies: 3Last Post: 06302010, 04:27 PM 
find the greatest and lowest number in 2D array
By le_albina@hotmail.com in forum New To JavaReplies: 2Last Post: 03302009, 11:09 PM 
how to right a program that find kth number in two sorted array?
By fireball2008 in forum New To JavaReplies: 8Last Post: 04222008, 03:21 AM
Bookmarks