The output of the following program is main() { static int x[] =…
2015
The output of the following program is
main()
{
static int x[] = {1,2,3,4,5,6,7,8};
int i;
for (i=2; i<6; ++i)
x[x[i]]=x[i];
for (i=0; i<8; ++i)
printf("%d", x[i]);
}
- A.
1 2 3 3 5 5 7 8
- B.
1 2 3 4 5 6 7 8
- C.
8 7 6 5 4 3 2 1
- D.
1 2 3 5 4 6 7 8
Attempted by 301 students.
Show answer & explanation
Correct answer: A
The array is initialized as {1, 2, 3, 4, 5, 6, 7, 8}. The first loop runs for i = 2, 3, 4, and 5. For i = 2, x[2] = 3, so x[x[2]] means x[3], and x[3] becomes 3. For i = 3, x[3] is already 3, so x[3] = 3; there is no change. For i = 4, x[4] = 5, so x[x[4]] means x[5], and x[5] becomes 5. For i = 5, x[5] is already 5, so x[5] = 5; there is no change. The final array is {1, 2, 3, 3, 5, 5, 7, 8}, so the printed output is 12335578.