Hey guys, what is up. In this particular post, we will be talking about the what is recursion? Also, we will see some examples of recursive function.

Updated on 1/10/2021

What is recursion?

Recursion is the procedure of repeating items in a way similar to itself at different times. In programming languages, if a program allows you for calling a function itself continuously within the same function, then it is known as a recursive function.

The C language uses recursion, i.e., a function for calling itself. But at the time of using a recursive function, everyone must be attentive to define an exit condition for the function. Otherwise, it will call itself infinite times and will become an infinite loop.

Recursive functions are extremely helpful for solving numerous arithmetic difficulties, like computing a factorial, creating Fibonacci series.

THE THREE LAWS OF RECURSION –

Every recursive algorithm should follow three main laws:

  1. A recursive algorithm should call itself, recursively.
  2. Recursive problem should have a base case.
  3. A recursive algorithm should change its value continuously and move toward the exit statement or base case.

A base case is a state that permits the algorithm to stop recursing. A base case is typically a difficulty that is too small to be solved directly. In the factorial problem, the base case is n=1.

We must organize a way for a change of statements so that the program moves toward the exit statement. A change of state means that specific data that the algorithm is using is modified. Normally, the data that illustrates our problem gets smaller in some way. In the factorial problem, n decreases.

FACTORIAL –

Program:

#include<stdio.h> 

 long fact(int x) 

  if (x == 0) 

    return 1; 

  else 

    return(x * fact(x-1)); 

   int main() 

  int num; 

  long factorial; 

  printf(“Enter a number: “); 

  scanf(“%d”, &num);  

   factorial = fact(num); 

  printf(“Factorial of is equals to %d\n”, factorial); 

  return 0; 

Output:

What is recursion-2

FIBONACCI SERIES –

Program:

#include<stdio.h>   

void fibonacci(int x)

{   

    static int x1=0,x2=1,x3;   

    if(x>0)

    {   

         x3 = x1 + x2;   

         x1 = x2;   

         x2 = x3;   

         printf(“%d “,x3);   

         fibonacci(x-1);   

    }   

}   

int main()

{   

    int x;   

    printf(“Enter the number of elements: “);   

    scanf(“%d”,&x);   

    printf(“Fibonacci Series: “);   

    printf(“%d %d “,0,1);   

    fibonacci(x-2);//n-2 because 2 numbers are already printed   

    return 0; 

}  

Output:

what is Recursion-1

In the upcoming post, you will be getting information related to Samsung A51 Simple smartphone. If you haven’t seen our previous post on what is function in c programming and actual and formal parameters in c then go and see our previous posts.


0 Comments

Leave a Reply

Avatar placeholder

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