Recursion In C Programming

Recursion is a process by which a function calls itself repeatedly until some specified condition has been satisfied.

Example:


Factorial of a number using recursion in C Programming.

#include<stdio.h>
intfactorial(int);
intmain()
{
intn;
printf("Enter a number");
scanf("%d",&n);
printf("Factorial of num :-%d is = %d",n,factorial(n));
return 0;
}
intfactorial(intn)
{
if (n==0) /terminating condition/
return 1;
else
return (nfactorial(n-1)); /recursively calling/ calling itself*/
}

Advantages of Recursion In C

  1. Recursion is a more elegant and requires few variables which make program clean.
  2. Recursion can be used for replacing complex nesting codings by dividing the problems into smaller problems of its sub type.
  3. Recursive process is used for repetitive competition in which each action is stated in terms of previous result. So,it is useful while constructing the data structures like linked list and doubly linked list etc.

Disadvantages of Recursion In C

  1. The proccess is fairly slower than its iterative solution. (Iteration means repetition of a sequence of operations)
  2. It is hard to think the logic of recursion function. So it is difficult to debug the code containing recursion.
  3. Each time you call a function, you use your memory allocation, due to which you may run out of memory.
  4. The recursive function calls are not executed immediately
  5. In order to solve a problem recursively it must fulfill following conditions
    A. The problem must be written in a recursive form
    B. The problem statement must include a stopping condition

So due to this reasons it has its drawback.

Check out another example too.

Sum of Natural Numbers Using Recursion in C Programming.

#include<stdio.h>
int sum(int n);
int main()
{
int number, result;
printf(" Enter the positive integer:");
scanf("%d", &number);
result= sum(number);
printf(" sum= %d", result);
}
int sum(int num)
{
if(num!=0)
return num+ sum(num-1); /* self call to function sum()*/
else
return num;
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here