#include using namespace std; // (2) Write a function called sum_m_to_n() that returns // the sum of integers from m to n. int sum_m_to_n( int m, int n ) { int sum = 0; for ( int i = m ; i <= n ; i++ ) { sum += i; } return sum; } // (1) Write a function called sum_1_to_n() that returns // the sum of integers from 1 to the given value n. int sum_1_to_n( int n ) { // just call the function above! return sum_m_to_n( 1, n ); #if 0 int sum = 0; for ( int i = 1 ; i <= n ; i++ ) { sum += i; } return sum; #endif } // (3) Write a function called m_to_the_n() that returns // the value m raised to the nth power. Do NOT // use the pow() function -- write your own! double m_to_the_n( double m, int n ) { double answer = 1; for ( int i = 0 ; i < n ; i++ ) { answer *= m; // m * m * m * ... } return answer; } // (4) Write a function called factorial() that returns // the factorial n! of given integer value n. // (n! is n * (n-1) * (n-2) * ... * 1) int factorial( int n ) { int answer = 1; for ( int i = n ; i >= 1 ; i-- ) { answer *= i; } return answer; } int factorial_using_recursion( int n ) { if ( n == 0 ) { return 1; } else // n > 0 { return n * factorial_using_recursion( n - 1 ); } } int main() { // test the factorial function: int x = 6; int result = factorial_using_recursion( x ); cout << x << "! is " << result << endl; // test function (2): int m = 3, n = 6; int sum = sum_m_to_n( m, n ); cout << "Sum of " << m << " to " << n << " is " << sum << endl; return 0; }