Thread: Using Arrays to Find Min and Max

1. Using Arrays to Find Min and Max

Hello fellow Programmers,

Right now, I am making an array and making a loop that finds the minimum and maximum numbers in the array. For some reason, the output does not find the min and max; instead, it prints out the first number in the array. Please guide me so I can solve this problem and get the code working.

Thanks

- SimeonTG

Code:
Java Code:
```public class MinAndMax {

public static void main(String[] args) {
int nums[] = new int[5];
int min, max;

nums[0] = 99;
nums[1] = -10;
nums[2] = 100123;
nums[3] = 18;
nums[4] = -978;

min = max = nums[0];
for (int i = 1; i > 5; i++) {
if (nums[i] < min) min = nums[i];
if (nums[i] > max) max = nums[i];
}

System.out.println("min and max: " + min + " " + max);

}```
Output:

Java Code:
`min and max: 99 99`

2. Senior Member
Join Date
Sep 2014
Location
MA, USA
Posts
399
Rep Power
6

Re: Using Arrays to Find Min and Max

The for loop never starts looping because the condition is not met. Therefore the values stick with the definition in line 13.

3. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

Re: Using Arrays to Find Min and Max

If you want to make it easy on yourself for testing, do the following.

Java Code:
`int [] nums = {99,-10, 100123, 18, -978};`
Then just iterate over the array using the enhanced for syntax.

Java Code:
```for (int v : nums) {
// do something with v.
}```
Note: if you want to alter the array then you must use the traditional loop.

loop is probably better since you can assign the first value of the array to min and max,
just as you have done.

Regards,
Jim
Last edited by jim829; 11-20-2015 at 02:57 PM.

4. Re: Using Arrays to Find Min and Max

Originally Posted by benji2505
The for loop never starts looping because the condition is not met. Therefore the values stick with the definition in line 13.
Oh yeah! Thanks dude. It got the problem solved.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•