in Programming in C edited by
9,445 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
in Programming in C edited by
9.4k views

2 Comments

#include<stdio.h>
int main()
{
    static int x[]={1,2,3,4,5,6,7,8};
    int i;
    for(i=0;i<8;i++)
    printf("%d ",x[i]);
    printf("\n");
    for(i=2;i<6;++i)
    {
        x[x[i]]=x[i];
        printf("\n  i=%d  x[%d]=%d",i,x[i],x[i]);
    }
    printf("\n");
    for(i=0;i<8;i++)
    printf("%d ",x[i]);
return 0;
}

Run this you will understand..!
1
1
I think there was a similar question asked this year in IIIT H entrance i.e PGEE
0
0

4 Answers

22 votes
22 votes
Best answer
 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

4 Comments

@vijay are we considering index of array starting from 0 ?

second confusion is no which are we taking for i is that index value or elements of array .?
0
0
@Amit  .. yes ...here start index for array is 0, because loop is running from 0 to 7 and we have total 8 elements in array x[].

and for x[i] ... i is being used as index value for array x[].
0
0
Can you tell when the value of 'i' is incremented as in the for loop it is given that it is preincrement

so will 'i' be incremented at the beginning of the loop or at the end of loop
0
0
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

1 comment

correct...good one
0
0
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

4 Comments

@shekhar : now u get my solution ? plse let me know
0
0

@Anjali_aspirant got you.

0
0
okie
0
0
0 votes
0 votes
1,2,3,3,4,5,6,7 according to me

1 comment

how...u got this..
2
2
Answer: