Predict the output in Turbo C (16-bit DOS environment):\n#include<stdio.h>\n\nint main()\n{\n int arr[5], i = 0;\n while(i < 5)\n arr[i] = ++i;\n\n for(i = 0; i < 5; i++)\n printf("%d, ", arr[i]);\n\n return 0;\n}

Difficulty: Easy

Correct Answer: 1, 2, 3, 4, 5,

Explanation:


Introduction / Context:
Understanding pre-increment (++i) inside assignments and how it interacts with loop control is a foundational C topic. This program fills an array while incrementing the index.



Given Data / Assumptions:

  • arr has 5 elements.
  • i starts at 0; the loop condition is i < 5.
  • The assignment arr[i] = ++i uses pre-increment.


Concept / Approach:
With pre-increment, ++i increments i first, then the incremented value is used. Because the index in arr[i] is evaluated before ++i changes i, the assignment stores values 1..5 into arr[0..4] respectively as the loop advances.



Step-by-Step Solution:
Start i=0: condition true → arr[0] = ++i → i=1; arr[0]=1.Next: i=1: arr[1] = ++i → i=2; arr[1]=2.Repeat until i=4: arr[4] = ++i → i=5; arr[4]=5.Loop ends when i becomes 5; printing yields 1, 2, 3, 4, 5,.



Verification / Alternative check:
Change to arr[i++] = i; and observe a different sequence; or use explicit increments to trace values.



Why Other Options Are Wrong:
They assume post-increment behavior or initial garbage values. There is no syntax error.



Common Pitfalls:
Confusing arr[i] = ++i with arr[++i] = i; mixing pre vs post increment side effects.



Final Answer:
1, 2, 3, 4, 5,

More Questions from Arrays

Discussion & Comments

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