Tuesday, December 8, 2020

Learn recursion for beginners.

 Learn recursion for beginners.


Recursion is a function that call itself. It is an important concept. Recursion should must have a base condition that stop it from further calling.


General syntax of recursion.


void fun(int x)

{

        //  logic

}

int main()

{

      fun(x);

     return 0;

}


When we call the recursion then printing is done at two time;

  1. Printing at calling time.
  2. Printing at returning time.


Printing at calling time:



#include<stdio.h>

void fun(int x)

{

if(x>0)

{

printf("%d",x);

fun(x-1);

}

}

int main()

{

int x = 3;

fun(x);

return 0;

}


Printing at returning time:


#include<stdio.h>
void fun(int x)
{
if(x>0)
{
fun(x-1);
printf("%d",x);
}
}
int main()
{
int x = 3;
fun(x);
return 0;
}


Difference between loop and recursion:


1. Loop is repetitive statement.
2. Recursion is also repetitive statement.But loop will have ascending phase and recursion will have both ascending and descending phase.




Types of recursion:

  1. Tail recursion
  2. Head recursion
  3. Tree recursion
  4. Indirect recursion
  5. Nested recursion


 1.Tail recursion:

This is type of recursion where everything performed at calling time.Function will not do anything at returning time.

Program:

#include<stdio.h>

void fun(int x)

{

if(x>0)

{

printf("%d",x);

fun(x-1);

}

}

int main()

{

int x = 3;

fun(x);

return 0;

}


2.Head recursion:


This type of recursion will perform everything at returning time.This will not do anything at calling time.

If the function is performing something at returning time it can't be easily converted into loop but it can be converted.

Program that explain head recursion:


#include<stdio.h>
void fun(int x)
{
if(x>0)
{
fun(x-1);
printf("%d",x);
}
}
int main()
{
int x = 3;
fun(x);
return 0;
}


3. Tree recursion.


In this type of recursion a function is called multiple time.

Program that explain tree recursion:


#include<stdio.h>
void fun(int x)
{
if(x>0)
{
printf("%d",x);
fun(x-1);
fun(x-1);
}
}
int main()
{
int x = 3;
fun(x);
return 0;
}


4. Indirect recursion.


In indirect recursion there may be more than one function calling each other in circular fashion.So that the first function calls second one and then second function calls third one and then third function again callback first function.


Then it become a cycle so it become recursion.


5. Nested recursion.

This is basically recursion inside recursion.


#include<stdio.h>

int fun(int n)

{

if(n>100)

{

return n-10;

}

else

{

return fun(fun(n+10));

}

}

int main()

{

int x = 3;

int d = fun(x);

printf("%d",d);

return 0;

}

Share this

0 Comment to "Learn recursion for beginners."

Post a Comment

If you have any doubts then let me know.