Why can my for each loop not print out the contents of an array but a for loop will?

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

Answers (2)

Sohan Soni
Sohan Soni

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

Aniket Thakur
Aniket Thakur

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

Related Questions