0

I tried doing:

for (int i=0; i<matrix.length; i++) {
  for (int j=0; j<matrix[].length; j++) {

but that doesn't work :(

Devoted
  • 177,705
  • 43
  • 90
  • 110

3 Answers3

8

Just index into the matrix using your current row.

for (int i=0; i<matrix.length; i++) {
  for (int j=0; j<matrix[i].length; j++) {
    // code
  }
}

This even factors in the possibility of a jagged array (i.e., a matrix with an inconsistent number of rows in the column).

Jeffrey Hantin
  • 35,734
  • 7
  • 75
  • 94
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
5
for (int i=0; i<matrix.length; i++) {
    for (int j=0; j<matrix[i].length; j++) {
aromero
  • 25,681
  • 6
  • 57
  • 79
2
for (int i=0; i<matrix.length; i++) {
  for (int j=0; j<matrix[i].length; j++) {

Notice the i I added.

However, it's best to cache both lengths while looping to avoid re-evaluation on each loop, which saves time at the only cost of one more int in memory (the fix still applies):

for (int i=0, il=matrix.length; i<il; i++) {
  for (int j=0, jl=matrix[i].length; j<jl; j++) {
Delan Azabani
  • 79,602
  • 28
  • 170
  • 210