Sunday, May 1, 2011

Finding smallest and largest number in an array (java)

public static void main(String[] args) {

int[] numbers = new int[10];
int x = 0;
int max,min ;
while (x < numbers.length) {
int random = (int) (Math.random() * 10);
numbers[x] = random;
x = x + 1;
}
x = 0;
while (x <numbers.length) {
System.out.println("Value of numbers[" +x+ "] is " +numbers[x]);
x = x + 1;
}

max = numbers[0];
min = numbers[0];
for (x=0;x<numbers.length;x++){
if(numbers[x]>max){
max=numbers[x];
}
else if(numbers[x]<min){
min=numbers[x];
}

}
System.out.println("Largest number is " +max);
System.out.println("Smallest number is " +min);


}

No comments:

Post a Comment

Chitika