+ 3

# Help with code (array)

Hello. Can someone help me understand why the output for this program is 6? static void Main(string[] args) { int[,] array = new int[2,2] {{1,1}, {2,1}}; int mult = 1; for(int i =0; i<2; ++i){ int sum=0; for(int j=0; j<2; ++j){ sum+=array[i,j]; } mult*=sum; } Console.WriteLine(mult); //output is 6

4 Answers

+ 13

// Please, for the love of cookies, enforce proper indentations.
int[,] array = new int[2,2] {{1,1}, {2,1}};
int mult = 1;
for (int i =0; i<2; ++i)
{
int sum=0;
for(int j=0; j<2; ++j)
{
sum+=array[i,j];
}
mult*=sum;
}
// for first loop, i is 0, sum gets added with 1 and 1 when j is 0 and j is 1 respectively, to become 2. This is then multiplied into mult. Variable mult now stores 2.
// for second loop, i is 1, sum gets reinitialised to 0, and then added with 2 and 1 when j is 0 and j is 1 respectively, to become 3. This is then multiplied into mult. Variable mult becomes 2 * 3, which is 6.
// code outputs mult, which outputs 6.

+ 5

Thank you very much

+ 5

Here are some cookies for the help. đȘ đȘ đȘ

+ 4

first mult = 1;
when i = 0:
sum = 0
j = 0 >> array[0,0] = 1 >> sum = 0 + 1 = 1;
j = 1 >> array[0,1] = 1 >> sum = 1 + 1 = 2;
then mult = 1 * 2 = 2;
and when i = 1:
sum back to zero
j = 0 >> array[1,0] = 2 >> sum = 0 + 2 = 2;
j = 1 >> array[1,1] = 1 >> sum = 2 + 1 = 3;
then mult = 2 * 3 = 6;
I hope you get it