goldschd@strose.edu Write a function to calculate n! (n-factorial) - / | 1 if n == 0 n! = < | n * (n - 1)! if n > 0 \ - Use a for loop -- an ITERATIVE approach: int factorial( int n ) { int result = 1; for ( int i = n ; i > 1 ; i-- ) { result = result * i; } return result; } Use a RECURSIVE FUNCTION approach: int factorial_recursive( int n ) { if ( n == 0 ) { return 1; } else { // n > 0 return n * factorial_recursive( n - 1 ); } } Write an integer power function: / p | 1 p == 0 n = < p-1 | n * n p > 0 \ int intpower( int n, int p ) { if ( p == 0 ) { return 1; } else { // p > 0 return n * intpower( n, p - 1 ); } } Recursion ------------------ Rules for writing recursive functions: (1) Handle the BASE CASE(S) first. This is your stopping point (e.g. when n == 0 or when size is 1) (2) Break the problem down into smaller and smaller pieces. (3) What needs to be done BEFORE calling the recursive function? (4) What needs to be done AFTER? (5) Make sure each recursive call progresses toward the base case. PRINT A VECTOR USING RECURSION: // main() calls print_vec() void print_vec( vector &v ) { print_vec_helper( v, 0 ); } void print_vec_helper( vector &v, int i ) { if ( i < v.size() ) { cout << i << " is " << v[i] << endl; print_vec_helper( v, i + 1 ); } // else (base case) nothing happens }