Consider the following code segment. int arr[] = {0,1,2,3,4}; int i=1,*ptr;…

2023

Consider the following code segment.
int arr[] = {0,1,2,3,4};
int i=1,*ptr;
ptr=arr+2;
arrange the following printf statements in the increasing order of their output.

(A)  printf("%d",ptr[i]);

(B)  printf("%d",ptr[i + 1]);

(C)  printf("%d",ptr[-i]);

(D)  printf("%d",ptr[-i+1]);

Choose the correct answer from the options given below :

  1. A.

    (C), (A), (B), (D)

  2. B.

    (C), (D), (A), (B)

  3. C.

    (D), (A), (B), (C)

  4. D.

    (A), (B), (D), (C)

Attempted by 104 students.

Show answer & explanation

Correct answer: B

Solution: Evaluate pointer arithmetic and compute each expression.

  • ptr = arr + 2, so ptr points to arr[2] = 2.

  • ptr[-i] = *(ptr - 1) = arr[1] = 1

  • ptr[-i+1] = *(ptr - 1 + 1) = *(ptr + 0) = arr[2] = 2

  • ptr[i] = *(ptr + 1) = arr[3] = 3

  • ptr[i+1] = *(ptr + 2) = arr[4] = 4

Increasing order of the printed values: printf("%d",ptr[-i]) -> 1, printf("%d",ptr[-i+1]) -> 2, printf("%d",ptr[i]) -> 3, printf("%d",ptr[i+1]) -> 4.

Therefore the expressions in increasing order are: ptr[-i], ptr[-i+1], ptr[i], ptr[i+1].

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Mppsc Assistant Professor