C – Recursion

After reading the Recursion topic, you will able to use Recursion in C programming, you will understand the theory and example also you will know the Advantages and Disadvantages.

The idea behind recursion is that sometimes a problem is too problematic or too complex to solve as it is too big. If the problem can be broken down into smaller forms of itself, we may be able to find a way to solve one of these smaller forms and then be able to find a solution to the complete problem.

The function call itself is known as recursive function and the recursion is the process where the function called itself. The recursive function also referred as self-called function. Whenever a function called from itself, then there will be an infinite loop. To break this infinite loop every recursive function must check the terminating condition and then decide whether to call the function again or not. The example below will show the way of writing this type of function in C programming.

Program (1): To To find the factorial of a number using recursive functions.

#include<stdio.h>
#include<conio.h>
void main()
{
 int n,f;
 printf("Enter any number : ");
 scanf("%d",&n);
 f=factorial(n);
 printf("Factorial = %d",f);
 getch();
 }
int factorial(int n)
{
if(n==0)
{
return(1);
}
else
{
return(n*factorial(n-1));
}
}

Output (1)

Enter any number : 5
Factorial = 120

Explanation:

The example above is to calculate factorial of number based on recursive function. The recursive function int factorial ( int n) is declared which call itself again and again. When terminates condition if (n==0) examined a true condition, the recursive function return factorial of a number as an integer value.

Recursion Advantages

  • Recursive function requires less coding.
  • In Recursion, we break down a complex problem into smaller ones whose answer we already know.

Recursion Disadvantages

  • Recursive function logic sometimes difficult to construct.
  • If proper coding is not done, then the recursive function may lead to infinite loop.
  • During recursive function calls, recursion requires more time and memory because of indirect computation of time and memory.

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering.

Leave a Reply

Your email address will not be published. Required fields are marked *