MarksCode
MarksCode

Reputation: 8584

Recursion Sum of Array

I'm trying to print out the result of my returned sum but for some reason it prints out 0, but when I check the sum inside the function its performing its objective correctly. For example if I pass in an array of 10 items each equal to their index (0...9) the sum inside the function is 45 but when I print it out back in main() it prints 0. I'm really confused to say the least.

Here is my function, which I call using:

printf("%d\n", addArray3(arrayA, 9, 0));

To clarify, arrayA is a pointer to an 10 item'd array of integers.

// Sums array using recursion
int addArray3(int (*arrayA)[], int n, int sum){
    if (n<0){
        return sum; 
    } else {
        sum += (*arrayA)[n];
    }
    addArray3(arrayA, --n, sum);
}

If anyone can clear this up I'd really appreciate it, thanks!

Upvotes: 1

Views: 144

Answers (3)

bunty
bunty

Reputation: 629

Check this modified recursion function with efficient use of pointers:

void addArray3(int *arrayA, int n, int* sum){
    if (n<0){
        return;
    } else {
        *sum += arrayA[n];
    }
    addArray3(arrayA, --n, sum);
}

int main ()
{
    int ar[] = { 1, 2, 3};
    int sum = 0;
    addArray3(ar, 2, &sum);
    printf("%d\n",sum);

    return 0;
}

Upvotes: 0

Stubborn
Stubborn

Reputation: 780

Try, like this,it's working for me in both the cases:

1) Storing the return value in int t. OR

2) Directly printing the return value.

#include <stdio.h>

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

//      t = addArray3(a,9,0);
//      printf("%d\n",t);
        printf("%d\n",addArray3(a,9,0));
}

int addArray3(int (*arrayA)[], int n, int sum)
{
        if (n<0)
        {
                return sum;
        }
        else
        {
                sum += (*arrayA)[n];
        }
        addArray3(arrayA, --n, sum);
}

Upvotes: -1

CraigM
CraigM

Reputation: 399

You are missing a return on the last line. Compile with all the warning on and it might find that for you.

Related question about this behaviour that covers whats going on here (not having a return): Implicit int return value of C function

Upvotes: 2

Related Questions