• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Can you please explain how output is 0 0 3 0

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
}
}

}
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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


:-)
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
reply
    Bookmark Topic Watch Topic
  • New Topic