0

# why is output of this code 12?

4 Answers

+ 8

It multiplies the third and second elements and replaces the first element with that value. 4*3 is 12. 12 is put in the array as the first element, and then the first element (12) is printed.

+ 4

int[] a ={1,4,3}; implies
a [0]=1
a [1]=4
a [2]=3
for(i=2;i>=1;i--)
a [0] *= a [i]
when i=2
a [0] *= a [2] => a [0] = a [0] * a [2]
a [0] = 1*4 = 4;
when i=1
a [0] *= a [1] => a [0] = a [0] * a [1]
a [0] = 4*3= 12;
Since there is only single statement after for loop, it will be only statement that will in the scope of the loop. Hence it will be executed and you will get the result as 12.

+ 3

int[] a ={1,4,3};
int i; {
for(i=2;i>=1;i--)
a[0] *= a[i];
System.out.println(a[0]);
In this code the for loop is basically updating the 0th element of the array a as multiplication of all its elements. Lets iterate through the loop to help you understand.
In the first iteration i=2
So the assignment is a[0] *= a[2];
That is a[0] =1*3 = 3
In the second iteration i is decremented so i=1
So the assignment is a[0] *= a[1];
That is a[0] =3*4 =12
Now i is decremented to 0 and so the loop ends as i>=1 evaluates to false.
So finally print value of a[0] which is 12

+ 2

int[] a = {1,4,3};
In the for-loop the first element of the array (1) gets multiplied by the third (3) and then by the second (4).
a[0] = 1*3*4 = 12
Notice that the for-loop doesnt has a block ( curly braces ) and thus only the first statement after the loop head is executed in the loop.