In C, evaluate the effects of pre-increment and post-increment on array elements and indices. For the array and statements below, what values are printed for i, j, and m? #include<stdio.h> int main() { int a[5] = {5, 1, 15, 20, 25}; int i, j, m; i = ++a[1]; j = a[1]++; m = a[i++]; printf("%d, %d, %d", i, j, m); return 0; }

Difficulty: Medium

Correct Answer: 3, 2, 15

Explanation:


Introduction / Context:
This question targets operator side effects: pre-increment (++x) vs post-increment (x++), and how these changes alter subsequent indexing into an array.


Given Data / Assumptions:

  • a = {5, 1, 15, 20, 25} so a[0]=5, a[1]=1, a[2]=15, a[3]=20, a[4]=25.
  • i, j, m are ints.


Concept / Approach:
Pre-increment changes the variable then yields the incremented value. Post-increment yields the current value, then increments it. Also, using i++ as an index uses the old i for access and increments afterward.


Step-by-Step Solution:

Start: a[1] = 1 i = ++a[1] -> a[1] becomes 2, i = 2 j = a[1]++ -> j = 2, then a[1] becomes 3 m = a[i++] -> use i=2 to index: m = a[2] = 15, then i becomes 3 Final: i=3, j=2, m=15


Verification / Alternative check:
Trace with a quick table of i and a[1] across each statement; results remain consistent with pre/post rules.


Why Other Options Are Wrong:

  • 2, 1, 15: j is not 1 because a[1] was already incremented to 2 before j = a[1]++.
  • 1, 2, 5: i is not 1 and m is not a[1] or a[0].
  • 2, 3, 20: j is 2 (post), and m uses index 2 not 3 during access.


Common Pitfalls:
Forgetting that i++ uses the old i for indexing before incrementing, and mixing up pre vs post effects on a[1].


Final Answer:
3, 2, 15

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion