mattfong

CS2370 Lab 8

May 30th, 2011
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. //Matthew Fong
  2. //Lab 8: recursion
  3. //Description: add up all the elements of an array with a recursive function
  4.  
  5. #include <iostream>
  6. using namespace std;
  7.  
  8. int sum(int a[], int s);
  9.  
  10. int main()
  11. {
  12. int sumofarray;
  13. int size;
  14.  
  15. cout << "Enter the size of your array: " << endl;
  16. cin >> size;
  17. cout << endl;
  18.  
  19. int array[size];
  20. cout << "Enter " << size << " numbers." << endl;
  21.  
  22. for(int i = 0; i < size; i++)
  23. {
  24. cin >> array[i];
  25. }
  26.  
  27. cout << endl;
  28.  
  29. sumofarray = sum(array, size);
  30. cout << "Sum of the array: " << sumofarray << endl;
  31. return 0;
  32. }
  33.  
  34. int sum(int a[], int s)
  35. {
  36. int sumofarray = 0;
  37.  
  38. if(s > 0)
  39. {
  40. sumofarray = a[0] + sum(a+1, s-1);
  41. }
  42.  
  43. else
  44. return sumofarray;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment