info@meritcampus.com    +91-85006-22255
...
`

Array Accessing754
What will be the output of the following program?
`class ArrayOutput{    public static void main(String s[])    {        int a[] = new int[50];        int i = 27 % 11;        int j = 5 * 3;        int k = j - i;        a[i] = i;        a[j] = j;        a[k] = k;        int sum = 0;        for(int l = 0; l < a.length; l++)        {            sum += a[sum++];        }        System.out.println("Sum = " + sum);    }}`

 A. Sum = 40 B. Sum = 30 C. Sum = 0 D. Compilation Error E. Throws ArrayIndexOutOfBoundsException
Topic:

### User comments below.All of them might not be correct.

Ans is E.
As we are repeating the loop for 50(length of array) times and adding the sum with the values 5,10,15 which results sum = 30 and we are incrementing variable sum for every iteration... As the loop iterates for 50 times it will cross the length of the array... So it will raise ArrayIndexOutOfBoundsException.

Posted by Gopinath Manchikanti    2015-01-09 12:12:40

I want to go with option C ... Lets start the Execution From Main .. At 1st step a is allocated with size 50... then At 2nd Step i is evaluated as 5 and then at 3rd step j is 15 and next at 4th step k is 10 ..... Now a[i] is a[5] which is 5 .. Next a[j] is a[15] which is 15 and a[k] is a[10] is 10... and in next step sum is set as 0.. Now Next thing is loop .. here we are running loop l is iterated b/n 0 and "size of a" which is "50"  Now entering the loop .... here we have a post increment "sum ++ " inside the square braces ..So... After Execution of Whole Statement Only it is Going to Execute .. So After that Sum will be "0" Only...  So... It will Run all the loop with SUM as ZERO ... So.. Output is Zero...

Posted by ?????????? ?????    2015-01-09 13:37:25

Option C execution starts from main it will create an array 'a' with size 50 and i=5,and j=15,k=14, a[5]=5,a[15]=15,a[14]=14, remaining all locations are 0, and sum=0,after enter into for loop it will iterate 50 loops. first iteration a[sum++] became a[1] and that value is 0 so after execution of sum+=a[sum++] again sum became 0 because sum value is 0 initially in 2nd iteration also a[sum++] value a[1]=0,again sum became value 0 like this after 50 iterations also sum value 0 that's it will print Sum=0

Posted by Bhagi Bhagyasri    2015-01-09 13:39:08

ans is c.

Posted by Shubham Bansal    2015-01-10 03:26:20

This dose is now closed and the winners are ?????????? ?????,  for 'First Correct Comment', ?????????? ?????,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Mânïshå Mùlchåndânï. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2015-01-12 05:14:49