Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //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;
- }
Advertisement
Add Comment
Please, Sign In to add comment