You are on page 1of 3

RECURSIVE FUNCTION

A recursive function is a function that calls itself either directly or indirectly through another function.

Example:

The factorial of a nonnegative integer n, written n! is the product n · (n-1) · (n-2) · … · 1


with 1! equal to 1, and 0! defined to be 1.

The factorial of an integer, n, greater than or equal to 0, can be calculated iteratively using for as follows:

factorial = 1;

for ( counter = n; counter >=1; counter-- )

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.

To illustrate on how to get the return value:


So how do you define a 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.

n! = n · (n-1)! //complex case

1! = 1 //base case

0! = 1 //base case

To implement the recursive function based on the recursive relationships,

int factorial(int n){

if(n==0 || n==1)

return 1; //base case

else

return n * factorial(n-1); //complex case

Based on the above definition, a recursive function is composed of a simple if-else statement.

Here is a complete program with a call to the factorial function:

Another Example:

The Fibonacci series

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.

This maybe defined recursively as follows:

fibonacci(0) = 0

fibonacci(1) = 1

fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)

Implementation:

#include<stdio.h>

/*Recursive fibonacci function*/

int fibonacci(int n);

int fibonacci(int n){

if(n==0 || n==1)

return n;

else

return fibonacci(n-1) + fibonacci(n-2);

main(){

int i,x,y,number;

printf("Enter the length:");

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.

Open the link below for a detailed discussion on recursive functions.

https://www.youtube.com/watch?v=kepBmgvWNDw

You might also like