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 .
The array is initialized as:
with indices .
The pointer is initialized to , which points to . Thus, throughout the execution of the loop.
In the loop for (i = 0; i < 5; i++), the expression added to sum in each iteration is:
Here:
*b - ievaluates to .*(b - i)points to .
Evaluating each iteration:
- :
- :
- :
- :
- :
Adding these values to sum (initially 0):
The program prints 10.
10
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.