If you're trying to print each element of the matrix once, then none of the solutions in the other answers [EDIT: I guess we're down to one answer now] is going to help. The most they will do is get rid of the stack overflow error, but the output is still not going to be close to what you need.
Assuming this is a homework assignment and you've been told to use recursion for some reason (in real life nobody would do that), you have to step back and think about this: just what do you want printMatrix(m,i,j)
to do? Presumably, you want to print the m[i][j]
element, and then call printMatrix
to print the rest of the matrix. When you call printMatrix
recursively to start the printing rest of the matrix, what do you want i
and j
to be? Probably, you want the same i
and the next column, j+1
, but not if j
is at the end of the row. Then you want ... I'll let you think about that. But I don't think you want printMatrix
to call itself twice. Instead, you want it to call itself only once (at most); you'll probably need an if
statement that looks something like
if(something)
printMatrix(something);
else
printMatrix(something different);
but it will still call itself only once (since it will pick one or the other).
I'll mention one other thing: you're comparing i
to the number of rows in the array (m.length
), but you're also comparing j
to the number of rows in the array. That's fine if you know this is a square matrix. But if you want to compare j
to the number of columns, compare it to m[i].length
, since m[i]
is itself an array (that represents one row of the matrix).