// // Program: array_sum // // Purpose: test recursive function for computing sum of // elements of an array. // // Input: // up to MAXSIZE integers from standard input. // (currently MAXSIZE=50.) // Output: // the sum of the integers entered, printed to standard // output. // // Observe that this is *not* the best way to compute the // sum of some numbers entered from standard input! the // point of this program, however, is to demonstrate use // of recursion. // #include #include // has EXIT_SUCCESS // Recursive function to compute sum of array elements. // Pre: n >= 0, and array a has at least n elements. // Post: returns sum of a[0] .. a[n-1]. int array_sum(int n, int a[]) { if (n == 0) return 0; else return a[n-1] + array_sum(n-1, a); } // Main program. int main(void) { const int MAXSIZE = 50; int a[MAXSIZE]; int n; cout << "Enter up to " << MAXSIZE << " integers, ctrl-D to end:\n"; n = 0; while ((n < MAXSIZE) && (cin >> a[n])) n++; if (n == 0) cout << "nothing entered!\n"; else cout << "sum of input integers = " << array_sum(n, a) << endl; return EXIT_SUCCESS; }