# Printing the Max and Min in an Array

• October 28th, 2010, 05:29 PM
bonbon242
Printing the Max and Min in an Array
Another one for you guys if you want to help me out... This program is supposed to print the maximum and minimum value in an array. It doesn't. There's a problem in my logic and I cannot figure it out! I've been staring at it too long.

I'm new to Java, that's why all these are pretty simple to you gurus... thoughts? :)

EDIT: I lied, I wanted first and second maximum numbers. Sorry :\$

Code Java:

``` class A3Q3b { public static void main (String[] args) { // DECLARE VARIABLES/DATA DICTIONARY int [] a; // GIVENS: the array of values int index; // INTERMEDIATES: index through array int first, second; // RESULTS: values of Max and Second Max   System.out.println( "Please input the array: " ); a = ITI1120.readIntLine();   // BODY OF ALGORITHM first = a[0]; second = a[0]; index = 1;   while (index > a.length) { if (a[index] < first) { second = first; first = a[index]; } else { if (a[index] < second) { second = a[index]; }   } index = index + 1; }   System.out.println("The maximum number is " + first); System.out.println("The second number is " + second); } }```
• October 28th, 2010, 05:59 PM
Zula
Re: Printing the Max and Min in an Array
Are your <'s and >'s backwards? And probably easier to use a for loop to count through an array

int min = a[0];
int max = a[0];

for(int i = 0;i<a.length;i++) {
if(a[i]>max) max = a[i];
if(a[i]<min) min = a[i];
}

if you wanted first and second highest, as it seems in the code, I would
int min = a[0];
int max = a[0];
int second = a[0];

for(int i = 0;i<a.length;i++) {
if(a[i]>max){
second = max;
max = a[i];
}
if(a[i]<min) min = a[i];
}
• October 29th, 2010, 08:28 AM
bonbon242
Re: Printing the Max and Min in an Array
That did it. Thanks a lot :)