+92 332 4229 857 99ProjectIdeas@Gmail.com

Power through recursion (C++ Tutorial)


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,
If base is 3 and exp is 0, then this function will return 1,
If base is 3 and exp is 1, then this function will return 3,
If base is 3 and exp is 2, then this function will return 9,
If base is 3 and exp is 3, then this function will return 27,
If base is 3 and exp is 4, then this function will return 81,
If base is 3 and exp is 5, then this function will return 243,
If base is 3 and exp is 6, then this function will return 729,
If base is 3 and exp is 7, then this function will return 2187,
If base is 3 and exp is 8, then this function will return 6561,
If base is 3 and exp is 9, then this function will return 19683.
Code of powerRecursive()

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++)
#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

0 comments: