 # Recursion In C Language

A function calling itself again and again to compute a value is known as recursive function or recursion function or recursion. Normally a function is called by the main program or by some other function but in recursion the same function is called by itself repeatedly.

Syntax :

void recursion()

{

recursion(); /* function calls itself*/

}

int main()

{

recursion();

return 0;

}

Uses of recursion function :

Recursion functions are written less number of statements.

Recursion is effective where terms are generated successively to compute value.

Recursion is useful for branching process. Recursion helps to create short code that would otherwise be impossible.

Recursive function is very useful to solve many mathematical problems like to calculate factorial of a number, generating Fibonacci series, etc.

Number Factorial :

Following is an example, which calculates factorial for a given number using a recursive function:

Program :

#include <stdio.h>

int factorial(int i)

{

if(i <= 1)

{             return 1;

}

return i * factorial(i - 1);

}

int  main()

int i;

printf(“enter a value for finding factorial value:”);

scanf(“%d”, &i);

printf(“Factorial of %d is %d\n”, i, factorial(i));

return 0;

}

Output :

Enter a value for finding factorial value : 5

Factorial of 5 is 120

Fibonacci Series :

Following is another example, which generates Fibonacci series for a given number using a recursive function :

Program :

#include <stdio.h>

int fibonaci(int i)

{

if(i == 0)

{

return 0;

}

if(i == 1)

{

return 1;

}

return fibonaci(i-1) + fibonaci(i-2);

}

int  main()

{

int i,n;

printf(“how many fibonacci's(range) u want:”);

scanf(“%d”, &n);

for (i = 0; i < n; i++)

{

printf(“%d\t%n”, fibonaci(i));

}

return 0;

}

Output :

How many fibonacci's (range) u want: 10

0   1   1   2   3   5   8   13   21   34

powered by social2s