Reputation: 733
I have a sample code which creates an "array" of size 10 and tries to initialize it with reverse values in a For loop e.g:(9,8,7,6,5...0):
int[] array = new int[10];
for (int i = array.length - 1, j = 0; i >= 0; i--, j++) {
System.out.println("Present value of i=" + i
+ " Present value of j=" + j);
array[j] = i;
System.out.println("Array:" + j + "=" + i);
}
for (int k : array) {
System.out.println(array[k]);
}
So far so good. This is the output from console which is perfect:
Present value of i=9 Present value of j=0
Array:0=9
Present value of i=8 Present value of j=1
Array:1=8
Present value of i=7 Present value of j=2
Array:2=7
Present value of i=6 Present value of j=3
Array:3=6
Present value of i=5 Present value of j=4
Array:4=5
Present value of i=4 Present value of j=5
Array:5=4
Present value of i=3 Present value of j=6
Array:6=3
Present value of i=2 Present value of j=7
Array:7=2
Present value of i=1 Present value of j=8
Array:8=1
Present value of i=0 Present value of j=9
Array:9=0
The issue is with For-each loop in the end which is just printing the values in array:
for (int k : array) {
System.out.println(array[k]);
}
The values printed array are 0,1,2...9 where it should be 9,8,7...0
When I use the regular For loop to print the array, it works normally. Am I missing some funny business here?
Upvotes: 3
Views: 791
Reputation: 433
This for loop, for (int k : array) is basically gives you the array value in detail this for loop is like -
int k = array[0] = 9 int k = array[1] = 8 .....
and again you are trying to print array[9] , array[8] which gives you result like 0,1,2...
replace
for( int
k : array){
System
.out
.println
(array[k]);
}
with
for(int
k : array){
System
.out
.println
(k);
}
Upvotes: 0
Reputation: 31699
Basically, since (int k : array)
causes k
to go through the values in the array, not the indexes, what you've done is equivalent to
System.out.println(array[array[0]]);
System.out.println(array[array[1]]);
System.out.println(array[array[2]]);
System.out.println(array[array[3]]);
...
System.out.println(array[array[9]]);
which isn't what you want.
Upvotes: 7
Reputation: 178363
You are already getting the values out of the array
with your foreach loop, which you are using as an index again into the array, yielding the values in order again.
Just print k
. Change
for (int k : array) {
System.out.println(array[k]);
}
to
for (int k : array) {
System.out.println(k);
}
End of the output:
9
8
7
6
5
4
3
2
1
0
Upvotes: 11