Reputation: 3
I have two loops that are intended to print of the contents of an array. Why does this work:
for ( int k = 0 ; k < array.length; k++){
System.out.print ( array[k] + " ");
}
and not this:
for ( int k : array ){
System.out.print ( array[k] + " ");
}
Upvotes: 0
Views: 26
Reputation: 1238
Use this, if you want to print index and value at that index.
int arr[] ={10,20,30};
int i = 0;
for ( int k : arr ){
System.out.println ( " element at index "+ i++ + " - " + k);
}
Upvotes: 0
Reputation: 68905
for ( int k : array ){
System.out.print ( array[k] + " ");
}
k here is the actual integer data in the array and not the index. You should do
for ( int k : array ){
System.out.print ( k );
}
Upvotes: 2