Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Printing the Max and Min in an Array

1. ## 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 :\$

``` 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:  " );

// 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);
}
}```

2. ## 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];
}

3. ## The Following User Says Thank You to Zula For This Useful Post:

bonbon242 (October 29th, 2010)

4. ## Re: Printing the Max and Min in an Array

That did it. Thanks a lot