In C, consider this function that modifies an array through a pointer. What is printed after the loop and why?
#include
void change(int b, int n)
{
int i;
for (i = 0; i < n; i++)
(b + 1) = (b + i) + 5; / note the constant +1 on the left /
}
int main()
{
int i, a[] = {2, 4, 6, 8, 10};
change(a, 5);
for (i = 0; i <= 4; i++)
printf("%d, ", a[i]);
return 0;
}
-
A7, 9, 11, 13, 15
-
B2, 15, 6, 8, 10
-
C2 4 6 8 10
-
D3, 1, -1, -3, -5
-
ENone of the above
Answer
Correct Answer: 2, 15, 6, 8, 10
Explanation
Introduction / Context:This question explores pointer arithmetic and the consequences of writing to a fixed index inside a loop. The left-hand side of the assignment always uses (b + 1) rather than (b + i), which repeatedly overwrites the same array element.
Given Data / Assumptions:
- Initial array a = {2, 4, 6, 8, 10}.
- Loop runs with i = 0..4 and executes the same target index
b[1]in each iteration. - Right-hand side reads different positions via
(b + i).
Concept / Approach:The statement (b + 1) = (b + i) + 5 means “store into a[1] the value a[i] + 5”. As i changes, new values overwrite a[1]. All other positions remain unchanged.
Step-by-Step Solution:i = 0 → a[1] = a[0] + 5 = 2 + 5 = 7 → a = {2, 7, 6, 8, 10}.i = 1 → a[1] = a[1] + 5 = 7 + 5 = 12 → a = {2, 12, 6, 8, 10}.i = 2 → a[1] = a[2] + 5 = 6 + 5 = 11 → a = {2, 11, 6, 8, 10}.i = 3 → a[1] = a[3] + 5 = 8 + 5 = 13 → a = {2, 13, 6, 8, 10}.i = 4 → a[1] = a[4] + 5 = 10 + 5 = 15 → a = {2, 15, 6, 8, 10}.
Verification / Alternative check:A debugger or print inside the loop will show a[1] being overwritten on each pass, ending at 15.
Why Other Options Are Wrong:"7, 9, 11, 13, 15" suggests each element incremented; the code modifies only a[1]. "2 4 6 8 10" implies no change, which is false. The negative series does not match any computed state.
Common Pitfalls:Assuming (b+1) was a typo for (b+i). Read the code literally for correct behavior.
Final Answer:2, 15, 6, 8, 10