Reputation: 13
this function is supposed to calculate the sum inclusive ie. sum(2, 5) should yield 2 + 3 + 4 + 5.
int sum(int m, int n) {
if (m != n) {
return m + sum(m++, n);
}
return n;
}
However, i get a run time error every time i run this code.
Upvotes: 0
Views: 227
Reputation: 253
Don't increment m while calling, instead pass m+1
int sum(int m, int n)
{
if(m != n)
return m + sum(m+1, n);
return m;
}
Upvotes: 0
Reputation: 35512
m++
returns the value of m
before incrementing, so it will infinitely recurse. You should call sum(m + 1, n)
instead. Also, you should consider changing m != n
to m < n
to prevent the case of m > n
from recursing infinitely.
Upvotes: 5