
CS2370 Lab 8
By:
mattfong on
May 30th, 2011 | syntax:
None | size: 0.78 KB | hits: 49 | expires: Never
//Matthew Fong
//Lab 8: recursion
//Description: add up all the elements of an array with a recursive function
#include <iostream>
using namespace std;
int sum(int a[], int s);
int main()
{
int sumofarray;
int size;
cout << "Enter the size of your array: " << endl;
cin >> size;
cout << endl;
int array[size];
cout << "Enter " << size << " numbers." << endl;
for(int i = 0; i < size; i++)
{
cin >> array[i];
}
cout << endl;
sumofarray = sum(array, size);
cout << "Sum of the array: " << sumofarray << endl;
return 0;
}
int sum(int a[], int s)
{
int sumofarray = 0;
if(s > 0)
{
sumofarray = a[0] + sum(a+1, s-1);
}
else
return sumofarray;
}