Question

Consider the following C program:

#include <stdio.h>
int main()
{
    int a[] = {2, 4, 6, 8, 10};
    int i, sum = 0, *b = a + 4;
    for (i = 0; i < 5; i++)
        sum = sum + (*b - i) - *(b - i);
    printf("%d\n", sum);
    return 0;
}

The output of the above C program is ________.

Official answer and solution
Official answer
10
From
Official GATE 2019 answer key

Solution

Evaluate the pointer arithmetic and array accesses inside the loop for each iteration i=0,1,2,3,4i = 0, 1, 2, 3, 4.

The array aa is initialized as:

a={2,4,6,8,10}a = \{2, 4, 6, 8, 10\}

with indices a[0]=2,a[1]=4,a[2]=6,a[3]=8,a[4]=10a[0] = 2, a[1] = 4, a[2] = 6, a[3] = 8, a[4] = 10.

The pointer bb is initialized to a+4a + 4, which points to a[4]a[4]. Thus, ∗b=10*b = 10 throughout the execution of the loop.

In the loop for (i = 0; i < 5; i++), the expression added to sum in each iteration is:

(*b−i)−*(b - i)(\text{*b} - i) - \text{*(b - i)}

Here:

  • *b - i evaluates to 10−i10 - i.
  • *(b - i) points to a[4−i]a[4 - i].

Evaluating each iteration:

  • i=0i = 0: (10−0)−a[4]=10−10=0(10 - 0) - a[4] = 10 - 10 = 0
  • i=1i = 1: (10−1)−a[3]=9−8=1(10 - 1) - a[3] = 9 - 8 = 1
  • i=2i = 2: (10−2)−a[2]=8−6=2(10 - 2) - a[2] = 8 - 6 = 2
  • i=3i = 3: (10−3)−a[1]=7−4=3(10 - 3) - a[1] = 7 - 4 = 3
  • i=4i = 4: (10−4)−a[0]=6−2=4(10 - 4) - a[0] = 6 - 2 = 4

Adding these values to sum (initially 0):

sum=0+1+2+3+4=10\text{sum} = 0 + 1 + 2 + 3 + 4 = 10

The program prints 10.

Final answer

10

Common trap

Confusing *b - i with *(b - i) or reversing the index order.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2019 Computer Science and Information Technology (CS)
Question
63 of 65, printed as CS Q.53
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.