Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can you please explain how output is 0 0 3 0

 
Deepa Neela
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic