C Programming language-C Recursion

C Recursion

The C programming has the capability like an iterating a set of statements ‘n’ number of times. A similar concept can be done using the Functions and such functions are called “Recursion” functions. There are lots of use cases with this Recursion function.

Recursion is also defined as a technique of replicating or repeating or doing again same activity in a similar way by calling it again and again. The concept of calling the function from itself is called Recursion and the function in which takes this possible is called a recursive function.

Syntax:

void rec_func(void) {

               rec_func();          /*Function calls itself */

}

int main(void) {

               rec_func();

               return 0;

}

C program allows you to do such calling of function within the same function i.e., called Recursion. While implementing recursion function in the program, you need to be very cautious in defining an exit or terminating condition from the recursive function or else it may end up in infinite loop.

Example 1:

Factorial Program

#include

int fact(int n) {

    if (n <= 1){

        return 1;

    }

    return n*fact(n-1);

}

int main()

{

    int f = 5;

    printf("The factorial of %d is %d", f, fact(f));

    return 0;

}

Output

The factorial of 5 is 120

Example 2:

Fibonacci  Program

#include

int fibo (int f){

    if(f == 0)

        return 0;

    if(f == 1)

        return 1;

    return fibo(f-1) + fibo(f-2);

}

int main(){

    int f;

    for (f=0; f<10; f++) {   

printf("\nFibonacci numbers are: %d\t", fibo(f));

    }

    return 0;

}

Output:

Fibonacci numbers are: 0

Fibonacci numbers are: 1

Fibonacci numbers are: 1

Fibonacci numbers are: 2

Fibonacci numbers are: 3

Fibonacci numbers are: 5

Fibonacci numbers are: 8

Fibonacci numbers are: 13

Fibonacci numbers are: 21

Fibonacci numbers are: 34