pango322
pango322

Reputation: 13

Infinite loop when calculating recursive sum

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

Answers (2)

Siva Rahul
Siva Rahul

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

Aplet123
Aplet123

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

Related Questions