Don't like ads? PRO users don't see any ads ;-)
Guest

CS2370 Lab 8

By: mattfong on May 30th, 2011  |  syntax: None  |  size: 0.78 KB  |  hits: 49  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }