Mark
Mark

Reputation: 39

Simple C++ recursion does not work properly - I just don't see why

I have a small C++ program which should just sum up the contents of an integer array. The debug output shows that the recursion function is called correctly. I even checked the address of the array - it's the same all over.

I fail to understand why that code puts out this odd number in the end. I'm obviously doing something wrong, but I don't get it. Does anybody have a pointer in the right direction?

#include <iostream>
using namespace std;

int arr_sum(int arr[], int idx) {
    // debug
    cout << "arr[" << idx << "] = " << arr[idx] << " (" << arr << ")" << endl;

    if (idx > 0) {
        return arr[idx] + arr_sum(arr, idx - 1);
    }
}

int main () {
    int a[10];
    a[0]=1; a[1]=2;a[2]=3;a[3]=4; a[4]=5;
    a[5]=6; a[6]=7;a[7]=8;a[8]=9; a[9]=0;

    cout << a << endl;   // debug
    cout << "Sum: " << arr_sum(a, 9) << endl;
}

Output:

0x7ffc7c3fc7e0
arr[9] = 0 (0x7ffc7c3fc7e0)
arr[8] = 9 (0x7ffc7c3fc7e0)
arr[7] = 8 (0x7ffc7c3fc7e0)
arr[6] = 7 (0x7ffc7c3fc7e0)
arr[5] = 6 (0x7ffc7c3fc7e0)
arr[4] = 5 (0x7ffc7c3fc7e0)
arr[3] = 4 (0x7ffc7c3fc7e0)
arr[2] = 3 (0x7ffc7c3fc7e0)
arr[1] = 2 (0x7ffc7c3fc7e0)
arr[0] = 1 (0x7ffc7c3fc7e0)
Sum: 6295692

Upvotes: 0

Views: 1278

Answers (2)

pm100
pm100

Reputation: 50110

if (idx > 0) {
    return arr[idx] + arr_sum(arr, idx - 1);
}

you forgot the terminating case

if (idx > 0) {
    return arr[idx] + arr_sum(arr, idx - 1);
} else return arr[0];

Upvotes: 1

Mooing Duck
Mooing Duck

Reputation: 66912

You forgot the base case: what does arr_sum return if idx is zero?

Right now, the function doesn't return anything, which is illegal. Turn up your compiler warnings, every compiler warns about this. When it executes, it ends up leaving a random value on the stack, which gets interpreted as the return value, and added to the other results.

Upvotes: 1

Related Questions