CPP Functions call itself

Function can call itself?

  • When function can call itself, it is called recursion.
  • You must keep in mind that when a function calls itself, a new copy of that function is running.
    Recursion example (power of a number):
    Source code Result
    #include <iostream>
    using namespace std;
    typedef unsigned short USHORT;
    typedef unsigned long ULONG;
    
    ULONG GetPower(USHORT n, USHORT power);
    
    int main()
    {
      USHORT number, power;
      ULONG answer;
      cout << "Enter a number: ";
      cin >> number;
      cout << "To what power? ";
      cin >> power;
      answer = GetPower(number,power);
      return 0;
    }
    // The GetPower function returns base 
    // raised to the power
    ULONG GetPower(USHORT base, USHORT power) {
      ULONG value=base;
      if (power == 1) {
        cout << base << " in power of " << power ;
        cout << " is: " << value << "\n";
       return value;
      }
      else {
        value= value * GetPower(base,power-1);
        cout << base << " in power of " << power ;
        cout << " is: " << value << "\n";
        return (value);
      }
    }
    Enter a number: 5
    To what power? 8
    5 in power of 1 is: 5
    5 in power of 2 is: 25
    5 in power of 3 is: 125
    5 in power of 4 is: 625
    5 in power of 5 is: 3125
    5 in power of 6 is: 15625
    5 in power of 7 is: 78125
    5 in power of 8 is: 390625
    You could use Recursion with care, as it could be very memory consuming.

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.