edited by
9,378 views
10 votes
10 votes

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]);
}
  1. 1 2 3 3 5 5 7 8
  2. 1 2 3 4 5 6 7 8
  3. 8 7 6 5 4 3 2 1
  4. 1 2 3 5 4 6 7 8
edited by

4 Answers

Best answer
22 votes
22 votes
 x[] = {1,2,3,4,5,6,7,8}

 for (i=2; i<6; ++i)
    x[x[i]]=x[i];

i= 2,

x[ x[2] ] = x[ 2]
x[ 3 ] = 3


i= 3,

x[ x[3] ] = x[ 3]
x[ 3 ] = 3                   // see for i=2


i= 4,

x[ x[4] ] = x[ 4 ]
x[ 5 ] = 5


i= 5,

x[ x[5] ] = x[ 5 ]
x[ 5 ] = 5                         // see for i=4


Hence array x[] = { 1, 2, 3, 3, 5, 5, 7, 8}

Ans- A

selected by
6 votes
6 votes

initially our array looks like this: 

1 2 3 4 5 6 7 8

at i=2

x[3] = x[2];  ===   x[3] == 3    ->     4 = 3  

1 2 3 3 5 6 7 8

at i=3
x[3] = x[3];   ---->   no change 

1 2 3 3 5 6 7 8

at i=4
x[5] = x[4];    

1 2 3 3 5 5 7 8

at i=5

x[5] = x[5];   ------>  no change 

at i=6  loop exit condition 

thus 

output at last: 

1 2 3 3 5 5 7 8
3 votes
3 votes
1 2 3 4 5 6 7 8

this is an array starting with index 0.

when i=2; x[2]==3

x[x[i]]=x[i]  => x[3]=3; // this will replace the value of x[3] by 3

i=3 ; x[3]==3

x[3]=3 

i=4 , x[4]==5

x[5]=5 // it will replace 6 by 5

i=5 ; x[5]==5

x[5]=5

Now the modified answer would be 12335578

edited by
Answer:

Related questions

9 votes
9 votes
5 answers
1
go_editor asked Jun 21, 2016
6,122 views
The for loopfor (i=0; i<10; ++i) printf("%d", i&1);prints0101010101011111111100000000001111111111
8 votes
8 votes
2 answers
2
go_editor asked Jun 21, 2016
7,632 views
Consider the following program fragmenti=6720; j=4; while (i%j)==0 { i=i/j; j=j+1; }On termination j will have the value4896720
0 votes
0 votes
1 answer
3
TusharKumar asked Dec 22, 2022
510 views
can anyone explain how the for loop works here..?
3 votes
3 votes
2 answers
4