# Least To Greates[ if statement and for loop]

• 08-08-2008, 07:25 PM
kris09
Least To Greates[ if statement and for loop]
Here is the program that i wrote what i want to do is order numbers from least to greatest with some if statements and print statements with the for loop what i cant figure out is the logic for the if statement. I can only compare 2 numbers not 5 HOW DO I DO THAT?? thanks for the help guys
:)

import java.util.Scanner;

public class LeastToGreatestArray {

public static void main(String []args) {
Scanner myScanner = new Scanner(System.in);
int [] myArray;
int num1, num2, num3, num4, num5;
myArray = new int [5];

System.out.print("First Number: ");
num1 = myScanner.nextInt();
System.out.print("Second Number: ");
num2 = myScanner.nextInt();
System.out.print("Third Number: ");
num3 = myScanner.nextInt();
System.out.print("Fourth Number: ");
num4 = myScanner.nextInt();
System.out.print("Fifth Number: ");
num5 = myScanner.nextInt();

myArray[0] = num1;
myArray[1] = num2;
myArray[2] = num3;
myArray[3] = num4;
myArray[4] = num5;
//System.out.print(MyArray[0]); check if it works
//System.out.print(MyArray[1]); check !!

if(myArray[0] < myArray[1]){
System.out.print(myArray[0] + "is less than" + myArray[1]);
}

}
}
• 08-08-2008, 07:34 PM
Norm
Quote:

can only compare 2 numbers
That's what arrays allow you to do. If you put all the numbers in an array, you can look at each one in turn by varying the index to the array. You can use multiple indexes to point to different parts of the array. Use a for() loop to move thru the contents of the array.
To visualize the problem use a piece of paper, make a list of a couple of numbers, set pointers(indexes) to two numbers, compare them and then move the pointers and/or the numbers around until you get the algorithm.
Quote:

order numbers from least to greatest
The above sounds like a 'sort'. Do a search here for code samples that do a sort