-1

I'm trying to do a program that will do a sum for an array. If i put a printf in the function, it returns right, but at the final the result is incorrect. Why?

 #include <stdio.h>
int summ(int a[100],int n)
{
    static int sum=0;
    static int i=0;

    if(i<n)
    {
        sum+=a[i];
        ++i;
        return (summ(a,n)+sum);
    }
}
int main()
{
    int b[100];
    int n,i,suma;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&b[i]);
    }
    suma=summ(b,n);
    printf("Suma=%d",suma);
    return 0;
}
Developper
  • 89
  • 1
  • 10

2 Answers2

4

Compiling your code with warnings enabled should yield the following output:

program.c:13:1: warning: control may reach end of non-void function [-Wreturn-type]

This means that your summ function lacks a base case - i.e. it does not specify what should be returned once n is reached.

Once you fix this problem, your code starts returning the correct value. However, your function would still need some fixing, because you should not be using static variables in it. Any static variable in a function makes the function non-reentrant, which is very bad. In particular, your function can be run only once; second invocation would yield an error, because neither i nor sum could be reset.

Here is a simple recursive implementation of what you are looking to build:

int summ_impl(int a[], size_t i, size_t n) {
    return i != n ? a[i] + summ_impl(a, i+1, n) : 0;
}
int sum(int a[], size_t n) {
    return summ_impl(a, 0, n);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

With recursion:

int summ(int *a, int n) {
    if (n-- > 0)//the n is equal to n-1 after check condition
        return (summ(a,n) + a[n]);//return the n-1 sum (recursion) + current value
    return (0);
}

This way, the function will call itself while it not equal to zero (so between n and 0) So we got: a = [1,2,3] the function will return

3 + sum before
  -> 2 + sum before
    -> 1 + sum before
      -> 0

When the function go back in the stack 0 + 1 + 2 + 3 -> 6