Consider the following C program: #include <stdio.h> int main() { int x[] =…
2024
Consider the following C program:
#include <stdio.h>
int main()
{
int x[] = {2, 4, 6, 8, 10};
int a, b = 0, *y = x + 4;
for (a = 0; a < 5; a++)
{
b = b + ((*y - a) - *(y - a));
}
printf("%d\n", b);
return 0;
}What will be the output of the above C program?
- A.
4
- B.
6
- C.
8
- D.
10
Attempted by 100 students.
Show answer & explanation
Correct answer: D
Concept
In pointer arithmetic, if y points to an array element, then *(y - a) reads the element a positions before y. By contrast, *y - a first reads *y and then subtracts the integer a.
Parentheses and the position of the dereference operator therefore determine whether subtraction acts on a pointer or on an integer value. An accumulator must be updated with the value produced in every loop iteration.
Application
Here y = x + 4, so y points to x[4] and *y remains 10. For a = 0, 1, 2, 3, 4, the expression (*y - a) - *(y - a) produces the following updates:
At a = 0: (10 - 0) - 10 = 0, so b becomes 0.
At a = 1: (10 - 1) - 8 = 1, so b becomes 1.
At a = 2: (10 - 2) - 6 = 2, so b becomes 3.
At a = 3: (10 - 3) - 4 = 3, so b becomes 6.
At a = 4: (10 - 4) - 2 = 4, so b becomes 10.
Cross-check
Since x[4 - a] = 10 - 2a, each increment is (10 - a) - (10 - 2a) = a. Therefore the total is 0 + 1 + 2 + 3 + 4 = 10, which agrees with the iteration trace. The program prints 10.
A video solution is available for this question — log in and enroll to watch it.