File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# enhanced for loop problem -- from a mock

Js Kaur
Greenhorn

Joined: Mar 31, 2012
Posts: 2
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

Joined: Aug 03, 2008
Posts: 9465

20

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...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
ayush raj
Ranch Hand

Joined: Jan 15, 2012
Posts: 60
Good example for the fundamentals . Each time the for loop modifies the contents of the array and the iterator works accordingly !!
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 20525

50

Js Kaur wrote:I got this code from a mock .....

Please QuoteYourSources -- meaning which mock?

Henry

I agree. Here's the link: http://aspose.com/file-tools

subject: enhanced for loop problem -- from a mock