recursive function

Hi . how can compute the sum of integer number in an array with recursive function.
Hi. I'll give you an example of how you can turn a for loop into a recursive function. Then, you'll have to show me some code if you want more help :P

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

void asdf_loop(int i, int imax)
{
    if (i<imax)
    {
        cout << "asdf " << i << endl;
        asdf_loop(i+1,imax);
    }

    return;
}

int main()
{
    cout << "iteration:\n";
    for (int i=0; i<5; i++)
    {
        cout << "asdf " << i << endl;
    }

    cout << "\nrecursion:\n";
    asdf_loop(0,5);

    cout << "\nhit enter to quit...";
    cin.get();
    return 0;
}

In order to do what you want, you may have to pass more parameters in your recursive function and maybe change it's return value.
int array_sum(int array[], int size)
{
if (size == 0)
return 0;
else;
return array[size] + array_sum(array, size - 1);
}

int main()
{
int a[] = { 4, 2, 2 };
cout << array_sum(a, 3) << endl;
return 0;
}

i Have problem in sum
array[size] /*...*/

This will go out of bounds of your array.
Also, remove the semicolon after the 'else' keyword.
Try to avoid the stack overflow.
Topic archived. No new replies allowed.