# Trying to find 3 largest numbers in an array using a single For loop

• February 5th, 2014, 09:55 PM
Trying to find 3 largest numbers in an array using a single For loop
Hello Java Gurus:

I am trying to find 3 largest numbers in an array using a single For loop but my following code is still showing randomly sorted numbers. Any help/suggestion will be much appreciated.

public class largest3 {

static int m, n, o;
static int array[] = new int[100];

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {
array[i] = (int) (Math.random() * 100);
}
m = array[0];
n = array[1];
o = array[2];
for (int i = 0; i < 10; i++) {
if (array[i] > m){
o = n;
n = m;
m = array[i];
}
else if(array[i] > n) {
o = n;
n = array[i];
}
else if(array[i] > o) {
o = array[i];
}

}
for (int i = 0; i < 10; i++) {
System.out.println(array[i]);
}
}
}
• February 6th, 2014, 04:27 AM
GregBrannon
Re: Trying to find 3 largest numbers in an array using a single For loop
Welcome to the Forum! Please read this topic to learn how to post code correctly and other useful tips for newcomers.

Fix your post, and give your variables better names. What does 'm', 'n', and 'o' mean?
• February 7th, 2014, 09:27 AM
Sambit
Re: Trying to find 3 largest numbers in an array using a single For loop
Hi, Your logic is not proper. Please modify your code and post it properly as mentioned by GregBrannon above.