Doubt in mcq question in pointers

In the piece of code, arr[ ][ ] is a 2D
array and assume that the
contents of the 2D
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);
A) Sum of all elements in the matrix
B) Sum of alternate elements in the matrix
C) Sum of the elements along the principal diagonal
D) None

my answer is option D.
but answer given was option C.
suggest me the answer and why

A 2-dimensional array is an array of arrays, so it’s stored like this in memory:

char v[2][3] = {{1,3,5},{5,10,2}};

Content: | 1 | 3 | 5 | 5 | 10 | 2
Address: v | v+1| v+2| v+3| v+4 | v+5
To access v[x][y], the compiler rewrites it as: * (v + y * M + x) (where M is the second dimension specified)
So here…* ( * (arr+i)+(i++)) gives the address of only the principle diagonal elements.

Hi Nitesh, the correct answer is C only. Let’s dry run this code on an arr =

arr = [ 1 2 3 ]
        [ 4 5 6 ]
        [ 7 8 9 ]

At first iteration,
i = 0, sum = 0
sum = sum + *( *(arr+i) + i++ ) ;
sum = sum + *( *(arr+0) + 0 ) ; // i is 1 now because of i++ ;
sum = sum + *((arr[0]) + 0 ) ;
sum = sum + (arr[0][0] ) ;
sum = 0 + 1 ;
sum = 1 ;

At second iteration,
i = 1, sum = 1
sum = sum + *( *(arr+i) + i++ ) ;
sum = sum + *( *(arr+1) + 1 ) ; // i is 2 now because of i++ ;
sum = sum + *((arr[1]) + 1 ) ;
sum = sum + (arr[1][1] ) ;
sum = 1 + 5 ;
sum = 6 ;

At third iteration,
i = 2, sum = 6
sum = sum + *( *(arr+i) + i++ ) ;
sum = sum + *( *(arr+2) + 2 ) ; // i is 3 now because of i++ ;
sum = sum + *((arr[2]) + 2 ) ;
sum = sum + arr[2][2] ;
sum = 6 + 9 ;
sum = 15 ;

every time sum += arr[i][i] is happening and arr[i][i] is the diagonal element. Hence c option is the correct one.

Hope this helps :slight_smile:

1 Like

Hey Nitesh,
As you are not responding to this thread, I am marking your doubt as Resolved for now. Re-open it if required.

Please mark your doubts as resolved in your course’s “ Ask Doubt ” section, when your doubt is resolved.

thank you, nice explanation

1 Like

thanks for this good explanation