# How to sum an array element using java

Page 1 of 1

## 5 Replies - 2963 Views - Last Post: 26 August 2009 - 08:58 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=122415&amp;s=0aa2edca1a50e53cd5049d4dd09141e9&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 emie

Reputation: 0
• Posts: 1
• Joined: 26-August 09

# How to sum an array element using java

Posted 26 August 2009 - 06:06 PM

public class AverageDayForm1{
static int l = 5;
public static int[] studentNo;
public static double average;

studentNo=new studentNo[5];
studentNo[0]=25;
studentNo[1]=15;
studentNo[2]=28;
studentNo[3]=17;
studentNo[4]=19;

sum=

public static void avg() {
int sum=0, i;
for(i=0; i<l; i++) {
sum += values[i];
}
average = (double) sum / (double)l;
}
public static void main(String args[]){
set_values();
avg();
System.out.println("The value is " + average);
}
}

Is This A Good Question/Topic? 0

## Replies To: How to sum an array element using java

### #2 mattman059

• Epic Awesomeness

Reputation: 15
• Posts: 538
• Joined: 23-October 06

## Re: How to sum an array element using java

Posted 26 August 2009 - 06:09 PM

What is the problem? Make sure you post your code in between code tags also please so it's easier to read.

### #3 pbl

• There is nothing you can't do with a JTable

Reputation: 8378
• Posts: 31,956
• Joined: 06-March 08

## Re: How to sum an array element using java

Posted 26 August 2009 - 06:27 PM

int sum = 0;
for(int i = 0; i < studentNo.lenght; i++)
sum += studentNo[i];

as you can see my answer is not easy to read at all

### #4 prankster

Reputation: 9
• Posts: 67
• Joined: 31-July 09

## Re: How to sum an array element using java

Posted 26 August 2009 - 07:47 PM

As a lover of options I will add the equivalent of pbl's code using for-each:

```int sum = 0;
for (int snum : studentNo)
{
sum += snum;
}

```

See how easy it was to read with code tags?
We have to give the new guy a hard time you know!

This post has been edited by prankster: 26 August 2009 - 07:52 PM

### #5 pbl

• There is nothing you can't do with a JTable

Reputation: 8378
• Posts: 31,956
• Joined: 06-March 08

## Re: How to sum an array element using java

Posted 26 August 2009 - 08:23 PM

prankster, on 26 Aug, 2009 - 06:47 PM, said:

As a lover of options I will add the equivalent of pbl's code using for-each:

```int sum = 0;
for (int snum : studentNo)
{
sum += snum;
}

```

See how easy it was to read with code tags?
We have to give the new guy a hard time you know!

and you used the [ code] tags !!!!
No money no candies

### #6 prankster

Reputation: 9
• Posts: 67
• Joined: 31-July 09

## Re: How to sum an array element using java

Posted 26 August 2009 - 08:58 PM

pbl, on 26 Aug, 2009 - 07:23 PM, said:

and you used the [ code] tags !!!!