user5947618
user5947618

Reputation:

Finding the sum of all elements in a 2D array

Trying to create a 2D array that will find the sum of all elements. I am not inputting my numbers into the 2D array since I am using a driver to check my work. So far I have this - however it will not complie. What am I doing wrong?

public static double sum2d (double[ ][ ] array2d)  
{
    int sum = 0;
    for (int row=0; row < array2d.length; row++)
    {
        for (int col=0; col < array2d[row].length; col++)
        {
            sum = sum + array2d [row][col];
        }
    }

    return sum;
}

Upvotes: 2

Views: 28551

Answers (4)

ozz
ozz

Reputation: 23

package Homeworks;

public class HomeWork86 { public static void main(String[] args) {

int[][] a = {
        {1,1,2}, 
        {3,1,2}, 
        {3,5,3}, 
        {0,1,2}  
    };
    int sum=0;
    for (int i=0; i<a.length;i++){
      for (int j=0;j<a[i].length;j++){
        sum+=a[i][j];

      }
      System.out.println(sum);
        sum=0;
    }

} }

Upvotes: 0

Divz
Divz

Reputation: 3

Declare sum as double instead of int

Upvotes: 0

Paul Boddington
Paul Boddington

Reputation: 37645

You are missing a brace after the method signature

public static double sum2d (double[ ][ ] array2d) {  <----- put that in.

Also, you need to declare sum as double.

double sum = 0;

Note that if a method returns double, and sum has type int, you can do return sum. The problem here is that sum + array2d [row][col]; is a double so can't be assigned back to an int without a cast (but that's not what you want to do).

Upvotes: 1

RaminS
RaminS

Reputation: 2239

Your method is declared to return a double but you are returning sum which is an int.

Edit: As @samrap stated in the comments, your code has formatting errors here. You are missing an opening brace {.

Upvotes: 7

Related Questions