Recursive Means Occurring Again and Again

What is Recursion?
The process in which a function calls itself direct or indirectly is called recursion and the corresponding role is called every bit recursive function. Using recursive algorithm, certain problems tin be solved quite hands. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.

A Mathematical Interpretation

Let us consider a problem that a programmer have to determine the sum of first northward natural numbers, there are several ways of doing that but the simplest approach is simply add the numbers starting from 1 to n. So the part simply looks similar,

arroyo(one) – Only calculation one by one

f(n) = one + 2 + 3 +……..+ n

merely there is another mathematical approach of representing this,

approach(two) – Recursive adding

f(n) = 1                  northward=one

f(n) = n + f(north-1)    n>1

There is a uncomplicated deviation between the approach (i) and approach(2) and that is in arroyo(2) the function " f( ) " itself is being called inside the function, so this phenomenon is named every bit recursion and the part containing recursion is chosen recursive function, at the finish this is a smashing tool in the hand of the programmers to code some problems in a lot easier and efficient way.

What is base condition in recursion?
In the recursive program, the solution to the base of operations case is provided and the solution of the bigger problem is expressed in terms of smaller problems.

int fact(int n) {     if (n < = ane) // base case         return 1;     else             return n*fact(n-i);     }

In the above example, base case for north < = 1 is defined and larger value of number tin can be solved by converting to smaller one till base example is reached.

How a particular problem is solved using recursion?
The thought is to represent a problem in terms of one or more than smaller bug, and add one or more base conditions that stop the recursion. For example, we compute factorial n if nosotros know factorial of (n-i). The base of operations case for factorial would be north = 0. Nosotros return 1 when n = 0.

Why Stack Overflow error occurs in recursion?
If the base instance is non reached or not defined, then the stack overflow trouble may arise. Permit us have an example to empathise this.

int fact(int n) {     // wrong base example (it may cause     // stack overflow).     if (n == 100)          render 1;      else         return n*fact(northward-1); }

If fact(10) is called, it will call fact(nine), fact(eight), fact(7) and so on but the number will never reach 100. So, the base case is non reached. If the memory is exhausted by these functions on the stack, information technology will cause a stack overflow mistake.

What is the difference betwixt directly and indirect recursion?
A role fun is called direct recursive if it calls the same function fun. A function fun is called indirect recursive if it calls another function say fun_new and fun_new calls fun directly or indirectly. Difference between direct and indirect recursion has been illustrated in Table 1.

          // An example of direct recursion          void directRecFun() {     // Some lawmaking....      directRecFun();      // Some lawmaking... }          // An example of indirect recursion          void indirectRecFun1() {     // Some code...      indirectRecFun2();      // Some code... } void indirectRecFun2() {     // Some code...      indirectRecFun1();      // Some code... }

What is difference between tailed and not-tailed recursion?
A recursive function is tail recursive when recursive call is the last thing executed by the function. Please refer tail recursion commodity for details.

How retentiveness is allocated to different function calls in recursion?
When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for a called function is allocated on top of retention allocated to calling function and different re-create of local variables is created for each function call. When the base instance is reached, the function returns its value to the office by whom it is chosen and memory is de-allocated and the procedure continues.
Let usa take the example how recursion works by taking a elementary office.

CPP

#include <$.25/stdc++.h>

using namespace std;

void printFun( int examination)

{

if (examination < i)

return ;

else {

cout << examination << " " ;

printFun(test - 1);

cout << test << " " ;

return ;

}

}

int main()

{

int test = three;

printFun(test);

}

Coffee

class GFG {

static void printFun( int test)

{

if (examination < 1 )

return ;

else {

System.out.printf( "%d " , test);

printFun(test - ane );

System.out.printf( "%d " , test);

return ;

}

}

public static void main(String[] args)

{

int test = 3 ;

printFun(test);

}

}

Python3

def printFun(test):

if (test < 1 ):

return

else :

print (test, terminate = " " )

printFun(test - one )

print (test, end = " " )

return

test = iii

printFun(test)

C#

using System;

form GFG {

static void printFun( int test)

{

if (examination < 1)

return ;

else {

Console.Write(test + " " );

printFun(test - 1);

Console.Write(examination + " " );

render ;

}

}

public static void Master(String[] args)

{

int test = 3;

printFun(test);

}

}

PHP

<?php

role printFun( $exam )

{

if ( $test < ane)

render ;

else

{

echo ( "$test " );

printFun( $test -1);

echo ( "$examination " );

return ;

}

}

$test = 3;

printFun( $test );

?>

Javascript

<script>

role printFun(test)

{

if (test < i)

return ;

else {

document.write(test + " " );

printFun(examination - 1);

document.write(test + " " );

return ;

}

}

let test = 3;

printFun(test);

</script>

Output :

3 2 i i 2 3

When printFun(3) is called from main(), retentiveness is allocated to printFun(iii) and a local variable test is initialized to 3 and statement 1 to iv are pushed on the stack every bit shown in beneath diagram. Information technology first prints '3'. In statement 2, printFun(2) is called and memory is allocated to printFun(2) and a local variable test is initialized to ii and statement 1 to 4 are pushed in the stack. Similarly, printFun(ii) calls printFun(1) and printFun(1) calls printFun(0). printFun(0) goes to if argument and it return to printFun(1). Remaining statements of printFun(i) are executed and it returns to printFun(2) so on. In the output, value from 3 to ane are printed and and so i to 3 are printed. The retentiveness stack has been shown in below diagram.

recursion

Now, permit'south talk over a few applied issues which tin can exist solved by using recursion and understand its basic working. For basic understanding please read the post-obit articles.
Basic understanding of Recursion.
Problem 1: Write a program and recurrence relation to discover the Fibonacci series of north where due north>ii .
Mathematical Equation:

north if n == 0, northward == 1;       fib(due north) = fib(n-1) + fib(n-ii) otherwise;

Recurrence Relation:

T(north) = T(n-ane) + T(n-2) + O(1)

Recursive program:

          Input:          n = 5          Output:          Fibonacci series of 5 numbers is : 0 one 1 2 iii

Implementation:

C++

#include <bits/stdc++.h>

using namespace std;

int fib( int n)

{

if (n == 0)

return 0;

if (n == i || n == 2)

return 1;

else

render (fib(north - 1) + fib(n - two));

}

int main()

{

int n = v;

cout<< "Fibonacci series of five numbers is: " ;

for ( int i = 0; i < n; i++)

{

cout<<fib(i)<< " " ;

}

return 0;

}

C

#include <stdio.h>

int fib( int north)

{

if (n == 0)

render 0;

if (northward == i || northward == 2)

return one;

else

render (fib(due north - 1) + fib(north - two));

}

int main()

{

int northward = 5;

printf ( "Fibonacci serial "

"of %d numbers is: " ,

n);

for ( int i = 0; i < n; i++) {

printf ( "%d " , fib(i));

}

return 0;

}

Java

import coffee.util.*;

class GFG

{

static int fib( int n)

{

if (due north == 0 )

return 0 ;

if (n == i || n == 2 )

return 1 ;

else

render (fib(north - ane ) + fib(n - 2 ));

}

public static void main(String []args)

{

int n = v ;

Arrangement.out.print( "Fibonacci series of 5 numbers is: " );

for ( int i = 0 ; i < north; i++)

{

System.out.print(fib(i)+ " " );

}

}

}

Python3

def fib(n):

if (n = = 0 ):

return 0

if (n = = ane or due north = = 2 ):

return 1

else :

render (fib(north - ane ) + fib(due north - two ))

n = 5 ;

print ( "Fibonacci series of v numbers is :" ,end = " " )

for i in range ( 0 ,n):

print (fib(i),terminate = " " )

C#

using Arrangement;

public grade GFG

{

static int fib( int north)

{

if (n == 0)

return 0;

if (north == 1 || north == two)

render i;

else

return (fib(northward - ane) + fib(n - two));

}

static public void Main ()

{

int n = 5;

Console.Write( "Fibonacci series of 5 numbers is: " );

for ( int i = 0; i < n; i++)

{

Console.Write(fib(i) + " " );

}

}

}

Javascript

<script>

function fib(northward)

{

if (north == 0)

render 0;

if (n == one || n == 2)

return 1;

else

return fib(n-one) + fib(north-2);

}

allow n = 5;

document.write( "Fibonacci serial of 5 numbers is: " );

for (allow i = 0; i < due north; i++)

{

document.write(fib(i) + " " );

}

</script>

Output

Fibonacci series of 5 numbers is: 0 1 ane two 3          

Here is the recursive tree for input 5 which shows a clear motion-picture show of how a big problem tin can be solved into smaller ones.
fib(n) is a Fibonacci office. The time complexity of the given program tin depend on the function call.

fib(n) -> level CBT (UB) -> 2^n-1 nodes -> 2^north function telephone call -> ii^n*O(1) -> T(n) = O(2^north)

For Best Case.

T(northward) =   θ(2^north\2)

Working:

Trouble two: Write a program and recurrence relation to find the Factorial of northward where n>2 .
Mathematical Equation:

1 if n == 0 or n == one;       f(n) = n*f(north-i) if n> i;

Recurrence Relation:

T(n) = i for n = 0 T(n) = 1 + T(n-i) for north > 0

Recursive Programme:
Input: n = 5
Output:
factorial of five is: 120
Implementation:

C++

#include <bits/stdc++.h>

using namespace std;

int f( int northward)

{

if (n == 0 || n == 1)

return 1;

else

return n * f(due north - 1);

}

int main()

{

int n = 5;

cout<< "factorial of " <<north<< " is: " <<f(north);

return 0;

}

C

#include <stdio.h>

int f( int n)

{

if (n == 0 || n == ane)

return 1;

else

return n * f(north - i);

}

int main()

{

int n = 5;

printf ( "factorial of %d is: %d" , due north, f(due north));

return 0;

}

Java

public course GFG

{

static int f( int due north)

{

if (n == 0 || n == 1 )

render 1 ;

else

render n * f(north - 1 );

}

public static void master(String[] args)

{

int n = 5 ;

Organisation.out.println( "factorial of " + n + " is: " + f(n));

}

}

Python3

def f(due north):

if (n = = 0 or north = = 1 ):

return ane ;

else :

render north * f(n - 1 );

if __name__ = = '__main__' :

n = 5 ;

impress ( "factorial of" ,n, "is:" ,f(north))

C#

using System;

class GFG {

static int f( int n)

{

if (n == 0 || n == 1)

return 1;

else

return n * f(n - one);

}

static void Main()

{

int n = 5;

Console.WriteLine( "factorial of " + northward + " is: " + f(northward));

}

}

Javascript

<script>

office f(due north)

{

if (due north == 0 || north == 1)

return i;

else

return north*f(north-one);

}

permit n = 5;

document.write( "factorial of " + n + " is: " + f(n));

</script>

Output

factorial of 5 is: 120

Working:

Diagram of factorial Recursion part for user input 5.

What are the disadvantages of recursive programming over iterative programming?
Annotation that both recursive and iterative programs have the same problem-solving powers, i.e., every recursive program can be written iteratively and vice versa is likewise true. The recursive plan has greater space requirements than iterative programme as all functions will remain in the stack until the base case is reached. It also has greater time requirements considering of function calls and returns overhead.

What are the advantages of recursive programming over iterative programming?
Recursion provides a clean and simple fashion to write code. Some bug are inherently recursive similar tree traversals, Tower of Hanoi, etc. For such problems, it is preferred to write recursive code. We can write such codes also iteratively with the assistance of a stack data construction. For case refer Inorder Tree Traversal without Recursion, Iterative Tower of Hanoi.

Output based practice issues for beginners:
Practice Questions for Recursion | Set one
Exercise Questions for Recursion | Set up 2
Practice Questions for Recursion | Set 3
Practise Questions for Recursion | Set 4
Practice Questions for Recursion | Set five
Practice Questions for Recursion | Set 6
Practice Questions for Recursion | Prepare 7
Quiz on Recursion
Coding Practise on Recursion:
All Manufactures on Recursion
Recursive Practice Problems with Solutions
This article is contributed past Sonal Tuteja. If you similar GeeksforGeeks and would like to contribute, you can likewise write an article using write.geeksforgeeks.org or post your article to review-team@geeksforgeeks.org. See your article actualization on the GeeksforGeeks chief page and help other Geeks.
Please write comments if you find anything incorrect, or y'all desire to share more information about the topic discussed above



madduxusseent.blogspot.com

Source: https://www.geeksforgeeks.org/recursion/

0 Response to "Recursive Means Occurring Again and Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel