• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

For each loop confusing

 
Gautham Muralidharan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The output I got was
2
0
0.

Bu I don't understand how I get it. Please explain.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gautham Muralidharan wrote:Bu I don't understand how I get it. Please explain.

You could add a few additional println statements to see what's going on in the first enhanced for loop (as the second one should be pretty straightforward).

For example it could be something like:

Hope it helps!
Kind regards,
Roel
 
Gautham Muralidharan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the idea Roel. Now I found it.



This is equivalent to


where x will 0,1,2 in each iteration.


As the integer array is not initialized array[x] will always be 0 when x=1 and x=2, which means array[array[x]]=array[0] when x=1 and x=2. So in each iteration, array[0] is assigned with c++, which makes it 2 and the remaining two elements remain zero.
 
Ganesh Patekar
Bartender
Posts: 694
23
Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Oracle Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes correct but remember integer ( Integer ) and int are different.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic