Thursday 22 April 2021

Recursion in C

Recursion is a process in which a function calls itself. In a programming language, if a program allows calling of a function inside the same function, then the function is termed as recursive function and this  process of calling itself is called Recursion.

There are two main requirements for a function to be recursive:

1. Terminating condition -  the function must return when the terminating condition is satisfied.

2. Recursive call - the function must call itself.

Example:-

int fun()

{

    ...

    ...

    fun();

    ...

    ...

}

Here we can see that, the function fun( ) calls itself.

 

C program:-

C program to calculate the the sum of the ‘nth’ number using recursion.

 

#include <stdio.h>

 

int fun(int n)

{

    if (n == 0)

        return 0;

    else

        return fun(n - 1) + n;

}

int main()

{

    int sum = 0, x;

    printf("number");

    scanf("%d", &x);

    sum = fun(x);

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

    return 0;

}




12 comments: