+ 2
Matrix multi dimensional arrays
This code is supposed to display the elements within the array, it works, but I had to use 3 nested for loops. In the instructions for this challenge it says to use 2 nested for loops, can anyone show me how I can do this using 3 nested for loops? public class Main { public static void main(String[] args) { int[][] matrix = { {8, 1, 6}, {3, 5, 7}, {4, 9, 0}, }; //output the numbers for (int x = 0; x < 3; x++){ System.out.println(matrix[0][x]); } for (int t = 0; t < 3; t++){ System.out.println(matrix[1][t]); } for (int q = 0; q < 3; q++){ System.out.println(matrix[2][q]); } } }
6 ответов
+ 7
Natanael ,
there is also a simplified for loop (for-each loop) that can be used:
https://code.sololearn.com/cFz98sYqIS3z/?ref=app
+ 4
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{8, 1, 6},
{3, 5, 7},
{4, 9, 0},
};
//output the numbers
for (int p = 0; p < 3; p++){ //outer loop start
for (int q = 0; q < 3; q++){ //nested inner loop
System.out.print(matrix[p][q]+" ");
} //inner loop ends
System.out.println();
} //outer loop ends..
}
}
//p represents rows
//q represents columns..Natanael
+ 1
Thank you so much, I thought about rows and columns right before I got your answer
0
Sorry I meant using 2 nested for loops
0
I'm thinking these are not nested at all
0
Thank you, I will try to remember this. The simplified loop is new to me, I think it's more like an abbreviated loop than a simplified loop.