+ 3
Enhanced for multidimensional
is it possible to use an enhanced for loop to iterate through all the elements in a multidimensional array? if so, how?
2 Respuestas
+ 3
Yes. You need two for loops; one for each dimension. Here's a code snippet:
int sum =0;
int nums[][] = new int[3][3];
// load the multi-dimensional array with values.
for ( int i = 0; i < 3; i++ ) {
for ( int j = 0; j < 3; j++ ) {
nums[i][j] = i*j;
// use enhanced for to print values
for ( int tmp[] : nums ) { // create a tmp array for 1st dimension
for ( int tmp1 : tmp ) { // 2nd dimension
System.out.println ( "Value is " + tmp1);
sum += tmp1;
}
}
System.out.println ( "Total is " +sum );
0
This was really useful. Thank you!