Implement a math class for practicing recursive functions Th

Implement a math class for practicing recursive functions The class should have the following functions: sum(int n);//calculate summation of n with a loop sum_r(int n);//calculate summation of n using recursion power(int n, int m);//calculate m raised to the power of n using a loop power_r(int n, int m);//calculate m raised to power of n using recursion Requirement: use the header file for function prototype. Don\'t forget to use preprocessor directives. Test your code in the main() function.

Solution

math.h

#ifndef MATH_H
#define MATH_H

class math{
   public:
       int sum( int n );
       int sum_r( int n );
       int power( int n, int m );
       int power_r( int n, int m );
};
  

#endif

math.cpp

#include \"math.h\"

int math::sum( int n ){
   int result = 0;
   for(int i = 1; i <= n; i++){
       result+= i;
   }
   return result;
}

int math::sum_r( int n ){
   if( n == 1 ){ return 1;}
   return n + math::sum_r(n-1);
}

int math::power( int n, int m ){
   int result = 1;
   for(int i = 1; i <= m; i++){
       result*= n;
   }
   return result;
}

int math::power_r( int n, int m ){
   if( m == 0 ){ return 1; }
   return n*math::power_r(n, m-1);
}


driver.cpp

#include \"math.h\"
#include <iostream>
using namespace std;

int main(){
   math c;
   cout << c.sum(5) << \" \" << c.sum_r(5) << endl;
   cout << c.power(5,2) << \" \" << c.power_r(5,2) << endl;

   return 0;
}

compile as g++ -o a driver.cpp math.cpp

 Implement a math class for practicing recursive functions The class should have the following functions: sum(int n);//calculate summation of n with a loop sum_
 Implement a math class for practicing recursive functions The class should have the following functions: sum(int n);//calculate summation of n with a loop sum_

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site