Tuesday 27 April 2021

Tail recursion in C

If a recursive function calls itself and that recursive call is the last statement in the function to execute then the recursion is known Tail recursion.

 

Structure of Tail recursion:-

int fun(int n)

{

    if( n >= 0)

    {

       ...

       ...

       fun(n-1);

    }

}

Note: All the statements in the function are executed before the recursive call.

 

Problem:-

C program to count number in descending order using Tail recursion.

 

#include <stdio.h>

 

int fun(int n)

{

    if (n > 0)

    {

        printf("%d\n", n);

        return fun(n - 1);

    }

}

int main()

{

    int a;

    printf("number");

    scanf("%d", &a);

    fun(a);

    return 0;

}

Output:-







2 comments: