Cathy Luo - 1 year ago 62

Java Question

I need help with a few nested for loop questions, because I don't understand how to obtain the correct answers. I need to know how to do these by calculator and pencil for upcoming tests.

- What is the output?

`String output = "";`

for(int a = 1; a < 3; a++)

for(int b = 1; b < 3; b++)

output += (a*b) + "";

out.println(output);

- What is the output?

`int total = 0;`

for(int c = 3; c < 9; c= c+3)

for(int d = 1; d <= c; d++)

total = total + d;

out.println(total);

I was told that #1 is 1224 and #2 is 27, but I don't know how to get those answers. Any explanations would be greatly appreciated. Thanks!

Answer

It's not an answerable question but to explain you, First statement will add the each result of multiplication in loop like, `1*1`

, `1*2`

, `1*3`

and again `2*1`

, `2*2`

and `2*3`

adding `""`

at last means a sort way to convert output into String to append it with `output`

. And answer will be **1224**

Second is also the same, but it adds the result instead of concatenating, and loops till the value of `d`

reaches to value of `c`

and the output will be **27** as you say.