Home >>C Tutorial >C Recursive Function

Recursive Function in C

Recursion in C

Recursion in C language is basically the process that describes the action when a function calls a copy of itself in order to work on a smaller problem. Recursive functions are the functions that calls themselves and these type of function calls are known as recursive calls. The recursion in C generally involves various numbers of recursive calls. It is considered to be very important to impose a termination condition of recursion. Recursion code in the C language is generally shorter than the iterative code and it is known to be difficult to understand.

Recursion cannot be applied to all the problem, but Recursion in C language is very useful for the tasks that can be generally be defined in terms of similar subtasks but it cannot be applied to all the problems. For instance: recursion in C can be applied to sorting, searching, and traversal problems.

As function call is always overhead, iterative solutions are more efficient than recursion. Any of the problem that can generally be solved recursively, it can be also solved iteratively. Apart from these facts, there are some problems that are best suited to only be solved by the recursion for instance: tower of Hanoi, factorial finding, Fibonacci series, etc.

Write a program to calculate the factorial number

#include <stdio.h>  
int factorial (int);  
int main()  
{  
    int num,fact;  
    printf("Enter any number to find factorial ");  
    scanf("%d",&num);  
    fact = factorial(num);  
    printf("factorial = %d",fact);  
}  
int factorial(int num)  
{  
    if (num==0)  
    {  
        return 0;  
    }  
    else if ( num == 1)  
    {  
        return 1;  
    }  
    else   
    {  
        return num*factorial(num-1);  
    }  
}  
Output : Enter any number to find factorial 5
factorial = 120

What is Recursive Function

The working of a recursive function involves the tasks by dividing them generally into the subtasks. Some specific subtask have a termination condition defined that has to be satisfied by them. In the next step, the recursion in C stops and the final result is derived from the function.

The base case is the case at which the function doesn’t recur in C and there are instances where the function keeps calling itself in order to perform a subtask and that is known as the recursive case. Here is the following format in which all the recursive functions can be written:

Example of Recursive function

Write a Program to print 10 number of Fibonacci Series

#include<stdio.h>  
int fibo(int);  
void main ()  
{  
    int x,f;  
    printf("Enter value of n number?");  
    scanf("%d",&x);  
    f = fibo(x);  
    printf("%d",f);  
}  
int fibo (int x)  
{  
    if (x==0)  
    {  
    return 0;  
    }  
    else if (x == 1)  
    {  
        return 1;   
    }  
    else  
    {  
        return fibo(x-1)+fibo(x-2);  
    }  
}  
Output : Enter value of n number? 10
55

Popular Tutorials