anon
anon

Reputation:

Using a for loop to iterate through a 2D array

I am attempting to write a loop to iterate through a 2D array and sum each sub-array.

So far my code is as follows:

int[][] data = { { 10, 20 }, { 20, 10 }, { 50, 60 }, { 45, 20 }, { 10, 35 }, { 25, 16 } };
int[] sumOfArrays = new int[5];

    for (int[] i : data) {
        int sum = 0;
        for (int x : i) {
            sum =+ x;
        }
        sumOfArrays[i] = sum;
    }

    System.out.println(sumOfArrays);

This is not possible due to a type mismatch: (i) int[] - int

How can I resolve this?

Upvotes: 2

Views: 128

Answers (3)

Bram
Bram

Reputation: 127

    int[][] data = { { 10, 20 }, { 20, 10 }, { 50, 60 }, { 45, 20 }, { 10, 35 }, { 25, 16 } };
    int[] sumOfArrays = new int[data.length];

    for (int i = 0; i < data.length; i++) {
        int sum = 0;
        for (int x : data[i]) {
            sum += x;
        }
        sumOfArrays[i] = sum;
    }

    System.out.println(Arrays.toString(sumOfArrays));

Upvotes: 0

Makoto
Makoto

Reputation: 106389

There are a few problems here. Let's start with the one that bit you the hardest.

for (int[] i : data) {
    int sum = 0;
    for (int x : i) {
        sum =+ x;
    }
    sumOfArrays[i] = sum;
}

Inside the context of these nested loops, i refers to an int[] reference, so you can't use it to index into anything.

In general, when dealing with foreach loops, you generally lose the ability to index into them, so you should use caution when you're attempting to do so.

To get that, you have to introduce a new variable. Also be sure to flip your assignment; you want += instead of =+, since the former is just assignment to a guaranteed positive value.

int idx = 0;
for (int[] i : data) {
    int sum = 0;
    for (int x : i) {
        sum += x;
    }
    sumOfArrays[idx++] = sum;
}

Next, your array is one element too short - you have six rows but you only allocate room for 5. Fix that size and then the above code will work fine.

Upvotes: 2

rgettman
rgettman

Reputation: 178253

You are attempting to treat i as if it were an index, but it's a value -- the int[] row you're currently on.

You can keep a separate index variable that is incremented at the end of the i for loop.

int index = 0;
for (int[] i : data) {
    int sum = 0;
    for (int x : i) {
        sum += x;  // +=, not =+
    }
    sumOfArrays[index] = sum;
    index++;
}

An alternative would be to switch to a "standard" for loop, so you have the index variable defined as part of the for loop, getting the int[] yourself.

Either way, you'll need to use Arrays.toString to print the contents of sumOfArrays at the end of your code.

Additionally, the length of sumOfArrays doesn't match the length of data, so you'll get an ArrayIndexOutOfBoundsException. Try

int[] sumOfArrays = data.length;

Upvotes: 1

Related Questions