// SumOfOdds.C // Mon Feb 10 13:20:22 EST 1997 // Burt Rosenberg // This program demonstrates recursion. #include int sumOfOdds(int largestOdd) { //ASSERT: largestOdd should be a positive odd number if (largestOdd<=1) { return 1 ; // base case of recursion } else { // else apply formulat S_i = S_{i-1} + o_i // where o_i is the i-th odd number, and S_j is // the sum of the first j odd numbers. return ( sumOfOdds( largestOdd-2 ) + largestOdd ) ; } } // end of function sumOfOdds void main() { int numberOfOdds ; // the polite part: prompt for input, set up // for output. cout << "Enter the number of odds to add: " ; cin >> numberOfOdds ; cout << "The sum of the first " << numberOfOdds << " odd numbers is: " ; if ( numberOfOdds <=0 ) { cout << 0 ; } else { // the formula for o_i, the i-th odd, is // o_i = 2*i-1 cout << sumOfOdds( 2*numberOfOdds - 1 ) ; } // add a newline to the output. cout << endl ; }