# Learn C++ - C++

A C++ function can call itself.

This ability is called recursion.

## Example

``````
#include <iostream>
using namespace std;
/*from w w  w. j  a va  2s.  com*/
void countdown(int n);
int main(){
countdown(4);           // call the recursive function
return 0;
}

void countdown(int n){
cout << "Counting down ... " << n << endl;
if (n > 0)
countdown(n-1);     // function calls itself
cout << n << "\n";
}
``````

The code above generates the following result.

## Example 2

Demonstrating the recursive function factorial.

``````
#include <iostream>
#include <iomanip>
using namespace std;
/*w  w w . j a  v  a2  s  .c o  m*/
unsigned long factorial( unsigned long ); // function prototype

int main()
{
// calculate the factorials of 0 through 10
for ( int counter = 0; counter <= 10; ++counter )
cout << setw( 2 ) << counter << "! = " << factorial( counter )
<< endl;
} // end main

// recursive definition of function factorial
unsigned long factorial( unsigned long number )
{
if ( number <= 1 ) // test for base case
return 1; // base cases: 0! = 1 and 1! = 1
else // recursion step
return number * factorial( number - 1 );
}
``````

The code above generates the following result.

## Example 3

``````
// Testing the recursive fibonacci function.
#include <iostream>
using namespace std;
//from   ww w  .j a va  2  s.c  o  m
unsigned long fibonacci( unsigned long ); // function prototype

int main()
{
// calculate the fibonacci values of 0 through 10
for ( int counter = 0; counter <= 10; ++counter )
cout << "fibonacci( " << counter << " ) = "
<< fibonacci( counter ) << endl;

// display higher fibonacci values
cout << "fibonacci( 20 ) = " << fibonacci( 20 ) << endl;
cout << "fibonacci( 30 ) = " << fibonacci( 30 ) << endl;
cout << "fibonacci( 35 ) = " << fibonacci( 35 ) << endl;
} // end main

// recursive function fibonacci
unsigned long fibonacci( unsigned long number )
{
if ( ( number == 0 ) || ( number == 1 ) ) // base cases
return number;
else // recursion step
return fibonacci( number - 1 ) + fibonacci( number - 2 );
}
``````

The code above generates the following result.

## Example 4

Testing the iterative factorial function.

``````
#include <iostream>
#include <iomanip>
using namespace std;
/*from w  ww.  ja v  a  2  s  .  c  o m*/
unsigned long factorial( unsigned long ); // function prototype

int main()
{
// calculate the factorials of 0 through 10
for ( int counter = 0; counter <= 10; ++counter )
cout << setw( 2 ) << counter << "! = " << factorial( counter )
<< endl;
} // end main

// iterative function factorial
unsigned long factorial( unsigned long number )
{
unsigned long result = 1;

// iterative factorial calculation
for ( unsigned long i = number; i >= 1; --i )
result *= i;

return result;
}
``````

The code above generates the following result.