Recursion in C

05 min read

Recursive Functions: A function which calls itself repeatedly until a specified condition is satisfied, is called a recursive function. The C programming language supports recursion functions, but when using recursion, programmers need to be careful to define an exit condition from the function, otherwise, it will go into an infinite loop. Recursion functions are very useful in calculating factorial of a number and generating fibonnaci series etc.

Example: Recursive function to find the factorial of 'n'.

#include
int factorial(int n)
{
    if(n<= 1 )
      return 1;
    else
    {
      retum(n*factorial(n-1));
    }
}

int main()
{
    int n;
    printf("Enter a number:");
    scanf("%d",&n);
    printf("Factorial is %d\n",factorial(n));
    getch();
    return 0;
}

Assume n=5, then factorial(5) is called from the main()

(n<=1) is false

In the else part, n*factorial(n-1) is evaluated.

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error