Javascript required
Skip to content Skip to sidebar Skip to footer

Define Recursion and Then Discuss Examples of Recursion in Eg Art and Nature

What is Recursion?
The process in which a part calls itself directly or indirectly is called recursion and the corresponding function is called as recursive office. Using recursive algorithm, certain bug can be solved quite easily. Examples of such issues are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.

A Mathematical Interpretation

Let us consider a trouble that a programmer have to determine the sum of starting time northward natural numbers, at that place are several ways of doing that but the simplest approach is but add the numbers starting from 1 to n. So the office just looks like,

arroyo(one) – Simply adding one past one

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

but there is another mathematical approach of representing this,

arroyo(2) – Recursive adding

f(north) = 1                  north=1

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

In that location is a elementary departure betwixt the approach (1) and approach(2) and that is in arroyo(2) the function " f( ) " itself is being called inside the function, and then this phenomenon is named equally recursion and the function containing recursion is chosen recursive function, at the terminate this is a great tool in the paw of the programmers to code some issues in a lot easier and efficient way.

What is base of operations status in recursion?
In the recursive plan, the solution to the base instance is provided and the solution of the bigger problem is expressed in terms of smaller bug.

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

In the above example, base case for n < = 1 is defined and larger value of number can exist 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 trouble in terms of one or more than smaller bug, and add one or more base weather that finish the recursion. For example, we compute factorial due north if we know factorial of (n-i). The base case for factorial would be n = 0. We render one when north = 0.

Why Stack Overflow error occurs in recursion?
If the base instance is not reached or not divers, and then the stack overflow problem may ascend. Permit us accept an example to understand this.

int fact(int n) {     // incorrect base instance (it may crusade     // stack overflow).     if (n == 100)          return 1;      else         return n*fact(n-one); }

If fact(10) is chosen, it will call fact(9), fact(8), fact(7) and and so on but the number will never attain 100. Then, the base case is not reached. If the memory is exhausted past these functions on the stack, it will crusade a stack overflow error.

What is the divergence between straight and indirect recursion?
A part fun is called directly recursive if information technology 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 Tabular array 1.

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

What is departure between tailed and non-tailed recursion?
A recursive function is tail recursive when recursive call is the concluding thing executed by the role. Please refer tail recursion article for details.

How retentivity is allocated to different function calls in recursion?
When any function is chosen from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for a called role is allocated on top of memory allocated to calling part and different copy of local variables is created for each role phone call. When the base of operations case is reached, the role returns its value to the function past whom information technology is chosen and memory is de-allocated and the process continues.
Permit us take the example how recursion works by taking a uncomplicated part.

CPP

#include <bits/stdc++.h>

using namespace std;

void printFun( int exam)

{

if (test < i)

render ;

else {

cout << exam << " " ;

printFun(examination - ane);

cout << test << " " ;

return ;

}

}

int primary()

{

int test = 3;

printFun(test);

}

Java

class GFG {

static void printFun( int exam)

{

if (examination < i )

render ;

else {

Organisation.out.printf( "%d " , examination);

printFun(exam - one );

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

return ;

}

}

public static void chief(String[] args)

{

int test = three ;

printFun(exam);

}

}

Python3

def printFun(test):

if (test < 1 ):

render

else :

print (exam, cease = " " )

printFun(exam - 1 )

print (test, terminate = " " )

return

test = 3

printFun(exam)

C#

using System;

grade GFG {

static void printFun( int test)

{

if (test < 1)

return ;

else {

Console.Write(exam + " " );

printFun(test - one);

Console.Write(test + " " );

return ;

}

}

public static void Main(Cord[] args)

{

int test = 3;

printFun(test);

}

}

PHP

<?php

role printFun( $test )

{

if ( $test < 1)

render ;

else

{

echo ( "$test " );

printFun( $exam -1);

echo ( "$test " );

return ;

}

}

$test = 3;

printFun( $test );

?>

Javascript

<script>

function printFun(test)

{

if (test < 1)

return ;

else {

certificate.write(test + " " );

printFun(test - 1);

document.write(test + " " );

return ;

}

}

let test = three;

printFun(exam);

</script>

Output :

three 2 1 1 2 3

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

recursion

Now, let's hash out a few practical problems which tin can be solved past using recursion and understand its basic working. For basic agreement please read the following articles.
Bones understanding of Recursion.
Problem 1: Write a program and recurrence relation to find the Fibonacci serial of northward where n>2 .
Mathematical Equation:

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

Recurrence Relation:

T(n) = T(north-1) + T(n-ii) + O(1)

Recursive programme:

          Input:          n = 5          Output:          Fibonacci serial of 5 numbers is : 0 ane 1 2 3

Implementation:

C++

#include <bits/stdc++.h>

using namespace std;

int fib( int n)

{

if (n == 0)

return 0;

if (north == 1 || n == ii)

return 1;

else

return (fib(n - 1) + fib(northward - 2));

}

int main()

{

int due north = 5;

cout<< "Fibonacci serial of 5 numbers is: " ;

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

{

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

}

render 0;

}

C

#include <stdio.h>

int fib( int due north)

{

if (northward == 0)

return 0;

if (n == ane || n == 2)

return 1;

else

return (fib(due north - 1) + fib(n - ii));

}

int main()

{

int n = five;

printf ( "Fibonacci series "

"of %d numbers is: " ,

n);

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

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

}

return 0;

}

Java

import coffee.util.*;

form GFG

{

static int fib( int n)

{

if (n == 0 )

return 0 ;

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

return 1 ;

else

return (fib(n - i ) + fib(due north - 2 ));

}

public static void main(Cord []args)

{

int due north = 5 ;

Organisation.out.print( "Fibonacci serial of 5 numbers is: " );

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

{

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

}

}

}

Python3

def fib(due north):

if (n = = 0 ):

render 0

if (n = = 1 or n = = 2 ):

return i

else :

return (fib(n - 1 ) + fib(n - 2 ))

northward = 5 ;

print ( "Fibonacci serial of five numbers is :" ,end = " " )

for i in range ( 0 ,n):

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

C#

using System;

public class GFG

{

static int fib( int northward)

{

if (due north == 0)

return 0;

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

return 1;

else

return (fib(n - 1) + fib(n - ii));

}

static public void Main ()

{

int due north = five;

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

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

{

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

}

}

}

Javascript

<script>

function fib(n)

{

if (n == 0)

return 0;

if (n == 1 || n == 2)

return ane;

else

return fib(n-1) + fib(due north-2);

}

allow n = 5;

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

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

{

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

}

</script>

Output

Fibonacci series of 5 numbers is: 0 i i ii 3          

Here is the recursive tree for input five which shows a clear picture of how a big problem can exist solved into smaller ones.
fib(n) is a Fibonacci office. The time complication of the given program can depend on the function call.

fib(n) -> level CBT (UB) -> 2^northward-1 nodes -> ii^n office call -> 2^n*O(1) -> T(n) = O(ii^n)

For Best Example.

T(northward) =   θ(ii^due north\two)

Working:

Problem 2: 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(n-ane) if n> ane;

Recurrence Relation:

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

Recursive Plan:
Input: n = 5
Output:
factorial of v is: 120
Implementation:

C++

#include <bits/stdc++.h>

using namespace std;

int f( int n)

{

if (north == 0 || n == one)

return 1;

else

return northward * f(due north - one);

}

int main()

{

int northward = 5;

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

render 0;

}

C

#include <stdio.h>

int f( int n)

{

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

return 1;

else

return due north * f(northward - 1);

}

int chief()

{

int n = v;

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

return 0;

}

Coffee

public class GFG

{

static int f( int n)

{

if (n == 0 || north == i )

return 1 ;

else

return n * f(n - 1 );

}

public static void main(Cord[] args)

{

int n = 5 ;

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

}

}

Python3

def f(n):

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

return 1 ;

else :

return north * f(north - one );

if __name__ = = '__main__' :

n = 5 ;

print ( "factorial of" ,northward, "is:" ,f(northward))

C#

using System;

class GFG {

static int f( int n)

{

if (north == 0 || n == one)

return 1;

else

return n * f(n - 1);

}

static void Principal()

{

int n = 5;

Panel.WriteLine( "factorial of " + n + " is: " + f(n));

}

}

Javascript

<script>

function f(n)

{

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

return i;

else

return due north*f(northward-1);

}

let n = five;

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

</script>

Output

factorial of 5 is: 120

Working:

Diagram of factorial Recursion role for user input v.

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

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

Output based practice problems for beginners:
Practise Questions for Recursion | Set 1
Exercise Questions for Recursion | Set 2
Practise Questions for Recursion | Gear up 3
Practice Questions for Recursion | Set four
Practice Questions for Recursion | Set 5
Practice Questions for Recursion | Set 6
Exercise Questions for Recursion | Set 7
Quiz on Recursion
Coding Practise on Recursion:
All Articles on Recursion
Recursive Practise Issues with Solutions
This article is contributed past Sonal Tuteja. If y'all like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your commodity to review-team@geeksforgeeks.org. See your commodity appearing on the GeeksforGeeks primary page and aid other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed to a higher place


marsdenfuraggion.blogspot.com

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