recursive template sum of an array

Hey guys I'm having trouble figuring out this function. Hopefully you can tell me my mistake. My teacher wants us to do a recursive function to sum the elements of an array with this prototype: T sum(T array[], int beg, int end);

I dont quite understand why we need a beginning and end instead of just a size. Anyway thats besides the point. can someone enlighten me?

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
  #include <iostream>
using namespace std;

template <class T>
T sum(T array[], int beg, int end);

const int SIZE = 10;
int ary[SIZE] = {3, 4, 5, 6, 7, 8, 9, 10 , 11 , 12};

template <class T>
T sum(T array[], int beg, int end)
{
	if(beg <= 0)
	
		return 0;
	else
	return array[beg -1] + sum(array,beg, end -1);
}

int main()
{
	int summ;
	int beg = 0;
	summ = sum(ary,beg, end);
	cout << "The sum of the array is: " << summ <<  endl;
	return 0;
}
	
This doesn't work by the way.
line 24 - I don't see that you've defined end?

line 13 - the base case of the recursion function - I think you want the function to go through all the elements of the array until you reach the end. You could either increment beg in the recursive call or decrement end. But you want to end up with beg == end, returning the value of the array at that element.

Right now you're starting beg at 0, so you're going to meet the base case you have in the first call of the function. And line 17 - if beg is 0, beg-1 is going to be out of bounds in the array.

This is what I have tried so far. Still dont really understand how this one works.
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
30
31
32
33
#include <iostream>
using namespace std;

template <class T>
T sum(T array[], int beg, int end);

const int SIZE = 10;
int ary[SIZE] = {3, 4, 5, 6, 7, 8, 9, 10 , 11 , 12};

template <class T>
T sum(T array[], int beg, int end)
{
	
	if(beg == end)
	
		return ary[beg];
	else
	++beg;
		return array[beg -1] + sum(array,beg,end - 1);


}

int main()
{
	int summ;
	int beg = 0;
	int end = 0;
	summ = sum(ary,beg, end);
	cout << "The sum of the array is: " << summ <<  endl;
	return 0;
}
	
1
2
3
4
5
6
7
8
9
10
11
12
13
14
template < typename T >
T sum( const T array[], int pos_first_elem, int pos_last_elem )
{
    if( pos_first_elem == pos_last_elem ) // if there is only one element
        return array[pos_first_elem] ; // return that element

    else // if there are two or more elements
    {
        int pos_second_elem = pos_first_elem + 1 ;

        return array[pos_first_elem] + // return the first element plus
                sum( array, pos_second_elem, pos_last_elem ) ; // the sum of the remaining elements
    }
}

http://coliru.stacked-crooked.com/a/c7c1a55775b3e95e
Thanks JLBorges
Topic archived. No new replies allowed.