• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

What is happening here?

 
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
 
Jart Bo
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

Sorry for the typo.
I got this question from one of the threads here in Javaranch but I can't find it anymore. So I'm just going to re-post it:



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



I am confused how the output below was produced. I hope someone would explain carefully. Thanks!

OutPut:
0
0
3
0
 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
we have this --

1st iteration -- i = arr[0] ---> i=1
inside loop -- arr[i]=0 which means arr[1]=0 (as i is 1)

2nd iteration -- i= arr[1] ---> i=0 (as arr[1] was set to 0 in 1st iteration)
inside loop -- arr[i]=0 which means arr[0]=0 (as i is 0)

3rd iteration -- i= arr[2] ----> i=3
inside loop -- arr[i]=0 which means arr[3]=0 (as i is 3)

4th iteration -- i=arr[3]--- i=0 (as arr[3] was set to 0 in 3rd iteration)
inside loop -- arr[i]=0 which means arr[0]=0 (as i is 0)

so now we have, from above,
arr[0]=0
arr[1]=0
arr[3]=0

and arr[2] = 3 (from the original array)

so when we reprint the array elements , we get 0,0,3,0


wow , I am happy with myself that I cracked it
it was a tough one
 
Slideshow boring ... losing consciousness ... just gonna take a quick nap on this tiny ad ...
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic