Gene Frank
Gene Frank

Reputation: 23

for-each loop index

I have this piece of code:

int[] tab2 = {1, 2, 3, 4, 5, 6 ,7, 8, 9, 0};
for(int i : tab2)
    System.out.print(i + " ");

int[] tab3 = {1, 2, 3, 4, 5, 6 ,7, 8, 9, 0};
for(int i : tab3)
    System.out.print(tab3[i] + " ");

The first loop gives me 1 2 3 4 5 6 7 8 9 0

while the second one gives me 2 3 4 5 6 7 8 9 0 1

how come? Isn't the first index of an array 0?

Upvotes: 0

Views: 389

Answers (3)

Adam Liss
Adam Liss

Reputation: 48330

In each case, the for loop causes i to take on each of the values in the array. The first loops prints each of those values, as you'd expect.

But in the second loop, the values are used as the indices into the tab3[] array.

As i takes on the values 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
the printed values are tab3[1], tab3[2], ..., tab3[0],
which, as you wrote, are 2, 3, 4, 5, 6, 7, 8, 9, 0, 1.

You'll get the values you expected if you loop i through the values from 0 to 9, like this:

for (i = 0;  i < 10;  ++i) 
  System.out.print(tab3[i] + " ");

Upvotes: 0

auselen
auselen

Reputation: 28087

In the second loop you are printing value by looking from tab3's items.

tab3[tab3[0]], tab3[tab3[1]], tab3[tab3[2]], ...

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117685

In the first iteration of the second loop, i equals to 1 .. and hence tab3[i] is 2.

Upvotes: 2

Related Questions