# Max and Min of Elements in Array

Page 1 of 1

## 4 Replies - 490 Views - Last Post: 17 May 2014 - 01:07 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=347097&amp;s=4dc97aca2b8bb538cdad8cde4eabfdc6&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 will1990

Reputation: 0
• Posts: 3
• Joined: 17-May 14

# Max and Min of Elements in Array

Posted 17 May 2014 - 11:54 AM

hi I cant get this code to work if wont find the right min and range and its printing out my max three times

this is what I got

``` public static void main(String[] args)
{

double [] Rainfall = new double[12];

Rainfall[0] = 77.4;
Rainfall[1] = 56;
Rainfall[2] = 61.8;
Rainfall[3] = 62.1;
Rainfall[4] = 57.1;
Rainfall[5] = 61.8;
Rainfall[6] = 67.9;
Rainfall[7] = 86.3;
Rainfall[8] = 65.1;
Rainfall[9] = 92.9;
Rainfall[10]= 76.5;
Rainfall[11]= 80.1;

double max = 0;
double min = 0;
double sum = 0;

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

System.out.println(" Max rainfall is " + max);
}
}

for(int i = 0; i < Rainfall.length; i++)
{
if(Rainfall[i] < Rainfall[0])
{
min = Rainfall[i];
}
}
System.out.println(" Min rainfall is " + min);

for(int i=0; i < Rainfall.length ; i++)
{
sum = sum + Rainfall[i];
}
double average = sum / Rainfall.length;
System.out.println("Average value of the Rainfall is : " + average);

System.out.println("The Range is : " + Part1.randomWithRange(min,max));
}
public static double randomWithRange(double min, double max)
{
double range = Math.abs(max - min);
return range;
}
}
```

Is This A Good Question/Topic? 0

## Replies To: Max and Min of Elements in Array

### #2 NormR

• D.I.C Lover

Reputation: 322
• Posts: 2,371
• Joined: 25-December 13

## Re: Max and Min of Elements in Array

Posted 17 May 2014 - 12:01 PM

Quote

its printing out my max three times

That's because the print statement is inside the loop.

### #3 will1990

Reputation: 0
• Posts: 3
• Joined: 17-May 14

## Re: Max and Min of Elements in Array

Posted 17 May 2014 - 12:12 PM

thank you

### #4 CasiOo

• D.I.C Lover

Reputation: 1524
• Posts: 3,401
• Joined: 05-April 11

## Re: Max and Min of Elements in Array

Posted 17 May 2014 - 12:37 PM

You keep comparing with the value at Rainfall[0] when finding min
``` if(Rainfall[i] < Rainfall[0])
```

Instead you should be comparing against the current min value

And why so many loops? You can do all of the above operations within one single loop

### #5 will1990

Reputation: 0
• Posts: 3
• Joined: 17-May 14

## Re: Max and Min of Elements in Array

Posted 17 May 2014 - 01:07 PM

thank you for all your help i got it to work thank you very much