Ammonium Ammonium - 7 days ago 6
C Question

Recursive function, depending on number of steps, gives different answers

first time user here, hope I didn't miss any similar questions to this one.

The problem I'm having is that we're supposed to write code that will use a recursive function to take an array(array1[n]), then create a second array(array2[n]) in which the members of array2 would be the sum of all elements left to them in the first array which are positive. array2[0] is to be =0, array2[1]=array1[0], array2[2]=array1[0]+array1[1],....

Problem is, I keep trying to think of an algorithm, but I keep coming back to the same code, and I'm no less stumped than before. I thought of a few ways to alter the recursion in order to fix it, but that just made it more broken.

#include <stdio.h>


int sum(int array[],int tmp)
{
if(tmp<0)
return 0;
else
return array[tmp] + sum(array,tmp-1);

}

int main()
{
int n;
scanf("%d",&n);
int a[n],b[n],i,j;
for(i=0;i<n;i++){
scanf("%d",&a[i]);
if(a[i]<0)
a[i]=0;


}
b[0]=0;
for(i=n-1;i>0;i--)
{
int sum1=0;
for(j=i-1;j>=0;j--)
sum1+=sum(a,j);

b[i]=sum1;

}
for(i=0;i<n;i++)
{
printf("%d ",b[i]);

}


return 0;
}

Answer

try this:

#include <stdio.h>

int sum(int array[],int tmp){
    if(tmp<0)
        return 0;
    else
        return array[tmp] + sum(array, tmp-1);
}

int main(void){
    int n;

    scanf("%d",&n);
    int a[n], b[n+1], i, j;

    for(i = 0; i < n; i++){
        scanf("%d", &a[i]);
        if(a[i] < 0)
            a[i] = 0;
    }

    b[0] = 0;
    for(i = 0; i < n; ++i){
        b[i+1] = sum(a, i);
    }

    for(i = 0; i <= n; i++){
        printf("%d ", b[i]);
    }
    puts("");
    return 0;
}