# Sum of an array row

Page 1 of 1

## 4 Replies - 22102 Views - Last Post: 23 December 2009 - 10:44 AMRate 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=146620&amp;s=69cf3f22b5db430bb773ee540884435f&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 AmateurC

Reputation: -5
• Posts: 71
• Joined: 12-June 09

# Sum of an array row

Posted 22 December 2009 - 12:47 AM

I am trying to write a program that computes the sum the row of each array. Any suggestions?
```import java.io.*;

class SumofaRow
{

public static void main ( String[] args ) throws IOException
{
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };

// declare the sum
int sum = 0;

// compute the sums for each row
for ( int row=0; row < data.length; row++)
{

for ( int col=0; col < data[row].length; col++)
{
sum = sum + data[col][];
}

// write the sum for this row
System.out.println(sum);
}

}
}

```

Is This A Good Question/Topic? 0

## Replies To: Sum of an array row

### #2 Riveted

Reputation: 14
• Posts: 87
• Joined: 03-December 09

## Re: Sum of an array row

Posted 22 December 2009 - 01:59 AM

You're missing a row number when accessing data, and you also have col in the wrong spot. Since you are basing your inner loop off of data[row], you need to have your call look like data[row][col].

### #3 AmateurC

Reputation: -5
• Posts: 71
• Joined: 12-June 09

## Re: Sum of an array row

Posted 23 December 2009 - 04:15 AM

I am still stumped. Do you mind posting a few code examples to illustrate your point?

### #4 KYA

• Wubba lubba dub dub!

Reputation: 3202
• Posts: 19,232
• Joined: 14-September 07

## Re: Sum of an array row

Posted 23 December 2009 - 06:53 AM

```sum = sum + data[row][col];

```

What do you think sum = sum + data[col][]; means?

How is the computer supposed to access an unidentified index?

### #5 waltf

Reputation: 7
• Posts: 10
• Joined: 23-December 09

## Re: Sum of an array row

Posted 23 December 2009 - 10:44 AM

You are also not resetting your sum variable to 0 after summing / printing the sum of each row,
```	// declare the sum
int sum = 0;

// compute the sums for each row
for ( int row=0; row < data.length; row++)
{

for ( int col=0; col < data[row].length; col++)
{
sum = sum + data[col][];
}

// write the sum for this row
System.out.println(sum);
}

```

should be:
```   // declare the sum
int sum = 0;

// compute the sums for each row
for ( int row=0; row < data.length; row++)
{
// reset the sum for the this row
sum = 0;

for ( int col=0; col < data[row].length; col++)
{
sum = sum + data[row][col];
}

// write the sum for this row
System.out.println(sum);
}

```