What does this program line print out? (tables (or matrices?))

Here's a question that I need to know the answer for. What does this program print out at the end?

As I've understood it, the values mx should get at [0], [1] and [2] are 0, 1 and 4 on both of those.

I've figured a whole lot of ways to calculate sum, for example (0+4+0) + (4+4+1) + (9 + 4+4), but none of those add up.

Code:

`int[][] mx = new int[3][3];`

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

mx[i][j] = i * j;

}

}

int sum = 0;

for (int i = 0; i < 3; i++) {

sum = sum + mx[2][i];

}

System.out.println(sum);

So two questions: what number does it produce and why?

Thanks. Your help is very much appreciated. :)-:

Re: What does this program line print out? (tables (or matrices?))

You have a 3x3 matrix

[x, x, x]

[x, x, x]

[x, x, x]

which is filled by your first loops.

i and j are 0 to 3. so you will fill the first line, than the second and the third. so, for the first line, it will be 0, 0 * everything is 0, so the first line is fully filled with 0

->

[0, 0, 0]

[x, x, x]

[x, x, x]

for the second line, i will be 1, j will be 0,1 and 2.

1*0 = 0

1*1 = 1

1*2 = 2

->

[0, 0, 0]

[0, 1, 2]

[x, x, x]

the last line is yours...you will get it, i`m sure :-)

so, in the loop at the lines 8 - 10, it will sum up only the values from "column" 2

0+2+x = ??

I hope it helps you

Re: What does this program line print out? (tables (or matrices?))

This sounds like a homework question. Asking us what it does is pretty much defeating the purpose of the assignment, isn't it?

Trace through it with a piece of paper and a pencil. What do you expect to happen?

Then put together a little program that tests that assumption. Did it match? If not, step through it with a debugger to figure out what the difference is.

Re: What does this program line print out? (tables (or matrices?))

Thanks eRaaaaa! Got it right, finally.

KevinWorkman, quilty as charged. Tried to figure it out for like 20 minutes until I gave up. Not a big deal really, it was one of a set of 10 questions, each correct answer giving one point. And at this course we can gain a maximum of 1400 or so points. A perfectionist in me though didn't want to leave it hanging :D