Babz
Babz

Reputation: 75

Java: find sum of 2d array of numbers

Ok, so this sounds simple. but its been playing with my head for a little while now.

I need to create a method which finds the sum of a 2d array of integers.

I need to create the method:

public static int sum(int[][] array) 

this is what i done so far:

public static int sum(int[][] array){
int sum1 = 0;
    for (int i : array)
        sum1 += i;

    return sum1;
}

But I'm getting an error 'incompatible types required int[] found int.'.
Anyone that can help me complete this challenge?

Thanks. Edit: an example array would be:

3 -1  4  0
5  9 -2  6 
5  3  7 -8

for now they will always be of this format (4x3).

Upvotes: 1

Views: 19910

Answers (6)

Arjun Kay
Arjun Kay

Reputation: 328

Since array is 2 dimensional, you cannot specify int i: array in the for loop. Modify your code like this:

public static int sum(int[][]array){
int sum1 = 0;
for (int[] arr : array)
    for(int i: arr)
        sum1+=i;

return sum1;
}  

EDIT:
To store sum of each row, make use of an integer array.

public static int[] sum(int[][]array){
int sum = 0;
int sumOfRow[] = new int[array.length];
for(int i=0;i<array.length;i++){
    sum=0;
    for(int num: array[i]){
        sum1+=num;
    }
    sumOfRow[i] = sum;
}

return sumOfRow;
}

Upvotes: 3

xingbin
xingbin

Reputation: 28269

You can not + an array directly, see jls:

If the type of either operand of a + operator is String, then the operation is string concatenation.

Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.

So, if none of the operands is String, the additive operator is only appliable for:

  • Byte, byte
  • Short, short
  • Character, char
  • Integer, int
  • Long, long
  • Float, float
  • Double, double

Solution

You can achieve this by nested loops:

public static int sum2D(int[][] matrix){
    int sum = 0;
    for (int[] array : matrix) {
        for (int element : array) {
            sum += element;
        }
    }
    return sum;
}

or create another method to calculate the sum of 1D array:

public static int sum2D(int[][] matrix){
    int sum = 0;
    for (int[] array : matrix)
        sum += sum1D(array);
    return sum;
}

public static int sum1D(int[] array){
    int sum = 0;
    for (int number : array)
        sum += number;
    return sum;
}

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56393

The logic inside the method should be:

for (int[] i : array)
   for(int num : i)
        sum1+=num;

i is a type int[] not an int. The second loop is to enumerate over the array i enabling us to access the numbers in there and add it to the sum1 variable.


Further, as of Java-8, you can accomplish the task at hand as follows:

public static int sum(int[][]array){
      return  Arrays.stream(array)
                    .flatMapToInt(Arrays::stream)
                    .sum();
}

Upvotes: 3

Connor J
Connor J

Reputation: 570

public static int sum(int[][] array) 
{
int sum1 = 0;
for (int row=0; row < array.length; ++row)
{
    for(int col=0; col<array[row].length; ++col)
    {
        sum1 = sum1 + array[row][col];
    }
  } return sum1;
}

more information can be found here: Finding the sum of the values in a 2D Array in C#

logic is still sound

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520888

The canonical way of doing this would be to just use two nested loops, each of which covers one dimension of your two dimensional array:

for (int r=0; r < array.length; ++r) {
    for (int c=0; c < array[r].length; ++c) {
        sum += array[r][c];
    }
}

Demo

Upvotes: 0

k_ssb
k_ssb

Reputation: 6252

Your array declared as int[][], which really means an array of int[]. That is, elements of array have type int[], which are themselves arrays (this is why array is a "2D" array). When you write a for-each loop, make sure that your types match up:

for (int[] innerArray : array) {
    // do things with innerArray, which is a 1D int[]
}

The full solution looks like this:

public static int sum(int[][] array) {
    int sum = 0;
    for (int[] innerArray : array)
        for (int i : innerArray)
            sum += i;
    return sum;
}

Upvotes: 0

Related Questions