Recursion
- When a function calls itself, new local variables and parameters are allocated storage (usually on the system stack), and the function code is executed with these new variables from the start.
- The existence of functions makes possible a programming technique called recursion.
- Recursion involves a function calling itself.
Example
#include <iostream>
using namespace std;
unsigned long factfunc(unsigned long); //declaration
int main()
{
int n; //number entered by user
unsigned long fact; //factorial
cout > n;
fact = factfunc(n);
cout << “Factorial of “ << n << “ is “ << fact << endl;
return 0;
}
// factfunc()
// calls itself to calculate factorials
unsigned long factfunc(unsigned long n)
{
if(n > 1)
return n * factfunc(n-1); //self call
else
return 1;
}
Output
Enter a number: 10
Factorial is 3628800
Function Overloading
- In this section, you will learn about one of C++’s most exciting features: function overloading. In C++, two or more functions can share the same name as long as their parameter declarations are different.
- In this situation, the functions that share the same name are said to be overloaded, and the process is referred to as function overloading.
- Function overloading is one way that C++ achieves polymorphism.
Example
#include <iostream>
using namespace std;
void f(int i);
int main()
{
f(10);
return 0;
}
void f(int i)
{
cout << " In f(int), i is " << i << '
';
}
Output
In f(int), i is 10