Search This Blog

Tuesday, April 28, 2020

Recursion full explaination in C Programming.

          C-Programming:-

In this tutorials, you will learn:-

Recursion:-


A function is called recursive when it calls itself. There are is always if statement in recursive function to force the function to return without the recursive call being executed otherwise the function goes in an indefinite loop.

For example:

//Write a program to print factorial of any given no using recursion.

#include<stdio.h>
int fact(int);
int main()
{
int n, r;
printf("enter any no: ");
scanf("%d",&n);
r= fact(n);
printf("factorial is = %d", r);
}
int fact (int x)
{
int f;
if(x==1)
return(1);
else
f=x*fact(n-1);
return(f) ;
}

OUTPUT:

enter any no: 3 
factorial is = 6

Types of factorial:-

There are 4 types of factorial are:-

1. Direct recursion:-

A function is called direct recursion if it calls the same function again.

For example:

structure of direct recursion 
fun ( ) {
    // some code
fun ( ) ;
   // some code
}

2. Indirect recursion:

A function (let say fun) is called indirect recursion if it calls another function (let say fun 2) and then fun 2 calls function direct and indirectly.
structure of indirect recursion

For example:

fun() {                        fun2( ){
 // some code                // some code
fun2( ) ;                     fun ( ) ;
// some code               // some code
}                                          }

3. Tailed recursion: 

A recursion function is said to tailed recursive of the recursive if the recursive call is the last thing done by the function there are is no need to keep records of the previous steps.

For example:

void fun(int n)
{
if(n==0)
return ;
else
printf("%d",n);
return fun(n-1) ;
}
main()
 {
fun(3);
return 0 ;
}

OUTPUT:

3  2  1

4. Not tailed recursion:

A recursion function is said to be not talked recursive. If the recursive calls are not the lost thing done by the function different returning back. There the some something left to execute.

For example:

void fun(int x)
{
if(x==0)
return 0 ;
fun(x-1);
printf("%d",x);
}
int main()
{
fun(3)
return 0 ;
}

OUTPUT:

1  2  3

Advantages of recursion.

* It will be useful when the same kind of job has to be continued for a finite number of inputs.
* This function is very useful in tree transversal and stack.
* We can solve complex tasks easily using recursion.

Disadvantages of recursion:

* It recursion function there are must be a contain somewhere in the function to return without the recursive call being executed.
* It is difficult to trace the logic of the function.
* It executed a little bit slow because to maintain the stack. 

Thanks for reading....... 

If anyone have any doubt to related this topic , Plese comment.   



Mr. abhijeet dwivedi

Developer

Hey, I'm Abhijeet

0 comments:

Post a Comment

If you have any doubt, please let me know