Enhanced for multidimensional | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

30th Nov 2016, 11:16 AM
Nielsen
Nielsen - avatar
2 Answers
+ 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 );
30th Nov 2016, 4:20 PM
David Zimmer
David Zimmer - avatar
0
This was really useful. Thank you!
30th Nov 2016, 11:06 PM
Nielsen
Nielsen - avatar