Recursion

Recursive Programming

Recursion is a programming technique in which a method calls itself, i.e a method is defined in terms of itself.

In recursion a function α calls itself directly or calls a function β that in turn calls the original function α The function α is called a recursive function.


Examples of recursion in use

Following are the code and implementation of some examples of recursion

Sum of first n integers using recursion

Code

int sum(int n){

int sumOfNums;

if(n == 1){

sumOfNums = 1;

}

else{

sumOfNums = n + sum(n - 1)

}

return sumOfNums

}

Test

Enter n:

Sum of first n nums:

N factorial using recursion

Code

int factorial(int n){

if(n == 1){

return n;

}

else{

return n*factorial(n-1);

}

}

Test

Enter N:

N! =

The Nth Fibonacci number using recusion

Code

int fibonacci(int n){

if(n ≤ 1){

return 1;

}

else{

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

}

}

Test

Enter N:

Nth fibonacci number =