Win a copy of Design for the Mind this week in the Design forum!

# Arrays

Abhi vijay
Ranch Hand
Posts: 509
Source:John Meyers Mock test

class P3
{
public static void main(String[] args)
{int []arr = new int[]{1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;
}
for ( int i : arr )
{
System.out.println(i);
}
}
}

The answer is 0030.Can anyone expalin.

geeta vemula
Ranch Hand
Posts: 208
see te following part of code and its execution

{int []arr = new int[]{1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;

}

a[1]=0 ---> {1,0,3,4}
a[0]=0 --->{0,0,3,4}
a[3]=0 ---> {0,0,3,0}
a[0]=0 --->{0,0,3,0}

iterate through the loop and print the value which gives 0030

Hopw this helps you.

Geeta Vemula

Patel Chintan
Ranch Hand
Posts: 80
Originally posted by Abhi vijay:
Source:John Meyers Mock test

class P3
{
public static void main(String[] args)
{int []arr = new int[]{1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;
}
for ( int i : arr )
{
System.out.println(i);
}
}
}

The answer is 0030.Can anyone expalin.

Hi abhi here is explaination :

Intial Values:
arr[0]=1
arr[1]=2
arr[2]=3
arr[3]=4

Now, how for loop executes:
1) step
i=arr[0]=1
that means =>arr[i]=arr[1]=0
arr[0]=1
arr[1]=0 <--- Effected
arr[2]=3
arr[3]=4

2) step
i=arr[1]=0
that means =>arr[i]=arr[0]=0
arr[0]=0 <--- Effected
arr[1]=0
arr[2]=3
arr[3]=4

3) step
i=arr[2]=3
that means =>arr[i]=arr[3]=0
arr[0]=0
arr[1]=0
arr[2]=3
arr[3]=0 <--- Effected

now Just print in next for looop.

Abhi vijay
Ranch Hand
Posts: 509
Thanks a lot guys.