Win a copy of JDBC Workbook this week in the JDBC and Relational Databases forum
or A Day in Code in the A Day in Code forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

For each loop confusing

 
Ranch Hand
Posts: 32
  • 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.
 
Sheriff
Posts: 11604
178
Hibernate jQuery Eclipse IDE Spring MySQL Database AngularJS Tomcat Server Chrome Java
  • 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
Ranch Hand
Posts: 32
  • 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.
 
Bartender
Posts: 1248
86
Hibernate jQuery Eclipse IDE Angular Framework Spring MySQL Database AngularJS Tomcat Server Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes correct but remember integer ( Integer ) and int are different.
 
Would you turn that thing down? I'm controlling a mind here! Look ... look at the tiny ad ...
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic