I have this code that keeps giving me stack overflow errors and I don't know how to fix it (i'm new to recursion). what is wrong with my code?
4 Answers
The
process(a, sum, row++, column);
unconditionally calls the function with exactly the same arguments due to the use of post-increment (hat tip to @fge for spotting this). This immediately leads to infinite recursion.
Once you fix this, you'll run into another problem: you are checking that row
equals a.length - 1
, and your code can make it exceed a.length - 1
.
process(a, sum, row++, column); // increment #1
process(a, sum, row++, column--); // increment #2
4 Comments
row + 1
in both calls to process
(as well as column - 1
in the second call). But note that process
is never called with the second increment value, so row
can never really exceed a.length - 1
on any call.This looks wrong:
process(a, sum, row++, column);
process(a, sum, row++, column--);
Note that the post-increment and post-decrement operators increment or decrement a variable, and then return the old value of the variable. So, in the first of these two lines, you are calling the method process
with the exact same values as the original call. That will then call the method again with the same values, etc., until the call stack overflows.
Comments
This line process(a, sum, row++, column);
calls process(a, sum, row, column)
and then
it increment row!
Same function with same parameters is called again and again therefore it overflow stack.
This should do the trick : process(a, sum, ++row, column);
It firsts increment it and then pass it as argument. But then your row will be incremented. If you do not want to do it, simply use : process(a, sum, row + 1, column);
, it call process function with incremented row meanwhile does not change your row in method it is called from.
1 Comment
row + 1
as the argument.You call:
process(a, sum, row++, column);
But you use the postfix ++
operator; as a result, the row
value as an argument to this function will not change on call --> infinite recursion if row
is not exactly equal to a.length - 1
.
Call:
process(a, sum, row + 1, column);
Also, check that in the following line you actually meant to be calling:
process(a, sum, row + 2, column);
and not:
process(a, sum, row + 2, column - 1);
or even:
process(a, sum, row + 1, column - 1);
Given your confused use of postfix increments/decrement operators, it is hard to tell what you mean to do...
Hint: in order to avoid that kind of errors in the future, make your method parameters, row
and column
, final
; you will not be able to modify them in the method's body...
alist
here?row
or decrementcolumn
; just userow + 1
andcolumn - 1
where appropriate.row
andcolumn
asfinal
in your method declaration... Then see how you would code your method in this case...