3 - Recursive Function.
3 - Recursive Function.
A recursive function is a function that calls itself either directly or indirectly through another function.
Example:
The factorial of an integer, n, greater than or equal to 0, can be calculated iteratively using for as follows:
factorial = 1;
factorial *= counter;
For the recursive definition of the factorial function, it is arrived at by observing the following
relationships:
n! = n · (n-1)! Example:
5! = 5 · 4 · 3 · 2 · 1
5! = 5 · (4 · 3 · 2 · 1)
5! = 5 · 4!
1! = 1
0! = 1
Note: You have to derive the recursive definition to easily define the recursive function.
Going back to the recursive definition, it is divided into two cases: complex and base. The complex case is
the replica of the problem, while the base case or cases are those with definite values. Below are the two
cases.
1! = 1 //base case
0! = 1 //base case
if(n==0 || n==1)
else
Based on the above definition, a recursive function is composed of a simple if-else statement.
Another Example:
0, 1, 1 , 2, 3, 5, 8, 13, 21, …
Begins with 1 and 1 and has a property that each subsequent Fibonacci number is the sum of the previous
two Fibonacci numbers.
fibonacci(0) = 0
fibonacci(1) = 1
Implementation:
#include<stdio.h>
if(n==0 || n==1)
return n;
else
main(){
int i,x,y,number;
scanf("%d",&number);
for(i=1;i<=number;i++)
printf("%d\t",fibonacci(i));
Recursion is an alternative of iteration (descending order). Because a recursive function repeatedly calls
itself, to terminate, the base case should be arrived. Thus on the complex case, a part is an update to the
parameter to arrive to the base case.
https://www.youtube.com/watch?v=kepBmgvWNDw