• Welcome to ForumKorner!
    Join today and become a part of the community.

[Tutorial][C++] Power through recursion

hotspice

Member
Reputation
0
Power through recursion
powerRecursive() calculates the power of a number recursively. It takes 2 parameters; first is the base and second is the exponent.
For example,
Code of powerRecursive()

Code:
unsigned long powerRecursive( int base , int exp )
{
      if ( exp == 0 )
            return 1;
      else
            return base * powerRecursive( base , exp - 1 );
}
Summary of powerRecursive()
powerRecursive() is a recursive function with 2 parts;
first part is the base case – if the exponent is equal to 0, then this function will return 1.
powerRecursive ( 0 ) = 1
Second part consists of recursive calls as mentioned below:
base * powerRecursive ( base , exp - 1 )
Example (C++)
Code:
#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

unsigned long powerRecursive( int base , int exp )
{
      if ( exp == 0 )
            return 1;
      else
            return base * powerRecursive( base , exp - 1 );
}

int main()
{
      for( int i = 0; i < 10; i++  )
            cout << 3 << "^" << i << ":" << powerRecursive( 3 , i ) << endl;
      cout << endl;

      _getche();
      return 0;
}
Output
3^0:1
3^1:3
3^2:9
3^3:27
3^4:81
3^5:243
3^6:729
3^7:2187
3^8:6561
3^9:19683