aspose file tools*
The moose likes Beginning Java and the fly likes Can you please explain how output is 0 0 3 0 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can you please explain how output is 0 0 3 0" Watch "Can you please explain how output is 0 0 3 0" New topic
Author

Can you please explain how output is 0 0 3 0

Deepa Neela
Greenhorn

Joined: May 01, 2008
Posts: 6
class test1 {

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);
}
}

}
Seamus Minogue
Ranch Hand

Joined: Jun 24, 2008
Posts: 41
Deepa,

Have you tried stepping through the code yet?

The problem is this:
arr[i] = 0;

The way this for next works is for each iteration "i" will BE the next value in the array. Not the index of the next item in the array.

So stepping through it:

Iteration 1:
i = 1
set arr[1] = 0
arr = 1,0,3,4

Iteration 2:
i = 0
set arr[0] = 0
arr = 0,0,3,4

Iteration 3:
i = 3
set arr[3] = 0
arr = 0,0,3,0



Then you print them correctly giving you 0 0 3 0


:-)
Paul Sisco
Greenhorn

Joined: Jun 15, 2008
Posts: 11
Originally posted by Seamus Minogue:
Deepa,

Have you tried stepping through the code yet?

The problem is this:
arr[i] = 0;

The way this for next works is for each iteration "i" will BE the next value in the array. Not the index of the next item in the array.

So stepping through it:

Iteration 1:
i = 1
set arr[1] = 0
arr = 1,0,3,4

Iteration 2:
i = 0
set arr[0] = 0
arr = 0,0,3,4

Iteration 3:
i = 3
set arr[3] = 0
arr = 0,0,3,0



Then you print them correctly giving you 0 0 3 0


:-)



In addition to the above comment, arrays are zero based. Just keep in mind that you start counting at zero. So your array looks a bit like this...if we were counting, that is...
element 0 = 1
element 1 = 2
element 2 = 3
element 3 = 4
Vikas Kapoor
Ranch Hand

Joined: Aug 16, 2007
Posts: 1374
Tricky question.

If you still have doubt use pencil and paper and debug the first for loop.

At first sight i thought we may get IndexOutOfBoundException.
[ June 25, 2008: Message edited by: Vishal Pandya ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can you please explain how output is 0 0 3 0
 
Similar Threads
Array...
Array Iteration Confusion
Arrays
array doubt
enhanced for loop problem -- from a mock