• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

enhanced for loop problem -- from a mock

 
Js Kaur
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got this code from a mock .....


output is ::

1
2
3
4
arr[1] = 0
arr[0] = 0
arr[3] = 0
arr[0] = 0
After ....
0
0
3
0


Why in the second loop array index's are like 1,0,3, 0 shouldn't it be arr[0], arr[1], arr[2], arr[3]
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When the loop runs the first time, ii contains 1 as arr[0] contains the value 1. The loop prints arr[1]=0 (as ii contains the value 1). Then you set arr[ii] to 0 i.e. arr[1] is set to 0.
Then when the loop run's 2nd time, ii contains the value of arr[1] which is 0. The loop prints arr[0]=0 (as ii contains the value 0). Then you set arr[ii] to 0 at this point ii is 0 so you set arr[0] to 0.
Then when the loop run's 3rd time, ii contains the value of arr[2] which is 3. The loop prints arr[3]=0 (as ii contains the value 3). Then you set arr[ii] to 0 at this point ii is 3 so you set arr[3] to 0.
Then when the loop run's 4th time, ii contains the value of arr[3] which is 0. The loop prints arr[0]=0 (as ii contains the value 0). Then you set arr[ii] to 0 at this point ii is 0 so you set arr[0] to 0...
 
ayush raj
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good example for the fundamentals . Each time the for loop modifies the contents of the array and the iterator works accordingly !!
 
Henry Wong
author
Marshal
Pie
Posts: 21415
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Js Kaur wrote:I got this code from a mock .....


Please QuoteYourSources -- meaning which mock?

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic