Question no 7 in MCQ-Pointers

Please explain question no 7

Q­7 In the piece of code, arr[ ][ ] is a 2­D array and assume that the
contents of the 2­D array are already filled up. What is stored in the
variable sum at the end of the code segment?
int arr[3][3];
int i, sum=0; i = 0; while(i<3) {
sum += * ( * (arr+i)+(i++)); }
printf(“sum:%d”, sum);

Hey @slow_motion, In this code *(arr+i)+(i++) this will results in the addresses where i can be 0,1,2 in the loop and * ( * (arr+i)+(i++)) results in the garbage values at these addresses and then we are simply adding these values using the variable sum.

Hope this would help :slight_smile:

@mr.encoder No it doesn’t help. Can you please elaborate with an example.

int arr[3][3];
int i, sum=0;
i = 0;
while(i<3)
{
sum += ((arr+i)+(i++));
}
printf(“sum:%d”, sum);
Options:
Sum of all elements in the matrix
Sum of alternate elements in the matrix
Sum of the elements along the principal diagonal
None of these
Answer: Sum of the elements along the principal diagonal
Explanation:
Observe that the unary operator ++ in the program is a post increment operator. Thus
the value of i gets incremented only after the execution of the statement.
Since arr is a 2-D array, arr represents a pointer to an array of pointers, where each
pointer in the array in turn points to a 1-D array(i^th pointer points to the starting location
of i^th row in the array). So, *(arr+i) represents the starting address of i^th row. This
implies *(arr+i)+i represents the address of i^th element in the i^th row, which is
basically a diagonal element.

1 Like

Got it…thank you…

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.