C Recursion

C  Recursion:

The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmer’s must need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.
These functions are very useful to solve many mathematical problems, such as calculating the generating Fibonacci series, factorial of a number etc.

Number Factorial

WAP to calculates the factorial of a given number by using a recursive function

#include<stdio.h>

int factorial1(unsigned int i1)

{

if(i1 <= 1)

{

return 1;

}

return i1 * factorial1(i1 – 1);

}

int main()

{

int i1 = 15; printf(“Factorial of %d is %d\n”, i1, factorial1(i1));

return 0;

}

Output
Factorial of 15 is 22528

Fibonacci Series:

WAP to generates the Fibonacci series for a given number by using a recursive function −
#include<stdio.h>

int fibonacci(int i1)

{

if(i1 == 0)

{

return 0;

}

if(i1 == 1)

{

return 1;

}

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

}

int main()

{

int i1;

for (i1 = 0; i1 < 10; i1++)

{

printf(“%d\t\n”, fibonacci(i1));

}

return 0;

}

Output

0

1

1

2

3

5

8

13

21

34

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *