Skip to content
Official PYQ · 2021

GATE CS 2021 Set 2 Q10 — Programming in C

Explain with AI

Consider the following ANSI C\text{ANSI C} program.

#include <stdio.h>
int main() 
{
    int arr[4][5];
    int  i, j;
    for (i=0; i<4; i++) 
    ​​​​​​{
        for (j=0; j<5; j++) 
        {
            arr[i][j] = 10 * i + j;
        }
    }
    printf(“%d”, *(arr[1]+9));
    return 0;
}

What is the output of the above program?

Choose one option
View worked solution

Answer: C

To find the output of the program, let's analyze how the 2D array is stored in memory and how the pointer arithmetic is evaluated.

1. Array Initialization

The array arr is declared as int arr[4][5], which has 44 rows and 55 columns. The elements are initialized using the formula:

arr[i][j]=10×i+j\text{arr}[i][j] = 10 \times i + j

Let's write down the values for the relevant rows:

  • Row 1 (i=1i = 1):
    • arr[1][0]=10\text{arr}[1][0] = 10, arr[1][1]=11\text{arr}[1][1] = 11, arr[1][2]=12\text{arr}[1][2] = 12, arr[1][3]=13\text{arr}[1][3] = 13, arr[1][4]=14\text{arr}[1][4] = 14
  • Row 2 (i=2i = 2):
    • arr[2][0]=20\text{arr}[2][0] = 20, arr[2][1]=21\text{arr}[2][1] = 21, arr[2][2]=22\text{arr}[2][2] = 22, arr[2][3]=23\text{arr}[2][3] = 23, arr[2][4]=24\text{arr}[2][4] = 24

2. Pointer Arithmetic and Memory Layout

In C, a 2D array is stored in row-major order as a contiguous block of memory.

  • The expression arr[1] decays to a pointer to the first element of the second row, i.e., &arr[1][0], and has the type int *.
  • Adding an integer kk to an int * pointer shifts it forward by kk elements of type int.

Therefore, we can map the pointer offsets starting from arr[1]:

arr[1]+0→&arr[1][0]arr[1]+1→&arr[1][1]  ⋮arr[1]+4→&arr[1][4]arr[1]+5→&arr[2][0](since each row has 5 elements)arr[1]+6→&arr[2][1]arr[1]+7→&arr[2][2]arr[1]+8→&arr[2][3]arr[1]+9→&arr[2][4]\begin{aligned} \text{arr}[1] + 0 &\to \&\text{arr}[1][0] \\ \text{arr}[1] + 1 &\to \&\text{arr}[1][1] \\ &\ \ \vdots \\ \text{arr}[1] + 4 &\to \&\text{arr}[1][4] \\ \text{arr}[1] + 5 &\to \&\text{arr}[2][0] \quad \text{(since each row has 5 elements)} \\ \text{arr}[1] + 6 &\to \&\text{arr}[2][1] \\ \text{arr}[1] + 7 &\to \&\text{arr}[2][2] \\ \text{arr}[1] + 8 &\to \&\text{arr}[2][3] \\ \text{arr}[1] + 9 &\to \&\text{arr}[2][4] \end{aligned}

3. Dereferencing

Dereferencing the pointer gives:

∗(arr[1]+9)=arr[2][4]*(arr[1] + 9) = \text{arr}[2][4]

Substituting the values:

arr[2][4]=10×2+4=24\text{arr}[2][4] = 10 \times 2 + 4 = 24

Thus, the program prints 24.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions