In the piece of code, arr[ ][ ] is a 2D array and assume that thecontents of the 2D array are already filled up. What is stored in th evariable 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
Pointers MCQ problem How is sum storing sum of elements of principal diagonal?
@dsingh200021 hey darshpreet
for 7th question
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.
Thanks for your reply but I am still confused
*(arr+i) represent the VALUE of ith element.
Lets have a 2d array {1,2
3,4}
Then *(arr+i) for i=0 should give value 1 and *(arr+i)+(i++) should give value 2
I WANT TO ASK IF *(ARR+I) GIVES THE VALUE OR ADDRESS because * is dereferencing pointer.
You have this as your last second line I think it should give value at that address because a dereferencing operator * is used