0

I have a function that takes an array a[] and its length n. I must calculate the sum of the numbers inside the array. I wrote this recursive function:

int somma(int a[], int n)
{
 if (n == 0) { return 0; }
 else {return a[n] + somma(a, n-1);}    
}

And I call it in my main() in this way:

int main() {   

 int array[5], ris;

 printf("Type the numbers of the array: \n");

 for(int i=0; i<4; i++)
 { 
   scanf("%d", &array[i]); 
 }

 printf("\nThe sum is: %d.", somma(array,4));

 getch();
 return 0;
}

If the array contains array = [2; 4; 7; 5] the printf must show 18 (2+4+7+5). By the way the function returns me 88, can you help me?

I am using wxDevC++.

1
  • Don't forget that a[0] is also an element of the array, which somma skips. Commented Oct 26, 2013 at 14:03

3 Answers 3

1

You are only reading the first four values in the array. array[4] contains garbage value

for(int i=0; i<5; i++) //change to 5
{ 
     scanf("%d", &array[i]); 
}

Your somma function is also wrong. It will always add 0 for arr[0].

 if (n == -1) { return 0; } //change to this
Sign up to request clarification or add additional context in comments.

Comments

1

You may try this:-

for(int i=0; i<=4; i++)
 { 
   scanf("%d", &array[i]); 
 }

Also correct your somma

 if (n == -1) 
 { 
    return 0; 
 }

Comments

1

If an array has n elements, then the last element has index n-1. Correct your somma function like this:

int somma(int a[], int n) {
    if (n <= 0) { 
        return 0;
    }

    return a[n-1] + somma(a, n-1);    
}

Additionally, there are two (minor) issues with your code:

  1. Variable declaration inside for head in for(int i=0; i<4; i++) is not allowed by C89, only C99 and C++. Probably DevC++ compiles it because the file is treated as C++, but you should know that it won't compile on GCC, unless you use the -std=c99 switch.
  2. getch is Windows-specific. On POSIX systems, use getchar instead.

2 Comments

Yes, you are right. I have updated the exit condition for recursion.
Note that the <= it's not strictly necessary (== would be ok), but it will avoid an infinite recursion in case of negative n.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.