The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. A method to solve the number digit problems using recursion is discussed in this article.
Two main components exist for any recursive function are:
- Base Case: A base case is a condition which stops the recursive function calls. A recursive function cannot be formed without a base case because the stack overflow error occurs when the base case is not defined as the function will keep on repeatedly calling itself. For a recursive solution, there can be more than one base case.
- Recursive Case: For all the other conditions apart from the base cases, the function calls itself with a new set of values such that after some finite recursive calls, the function finally calls for a base case and stops itself.
Let’s visualize the recursion by extracting individual digits from a given number. This is the basic step in performing many other mathematical operations.
Below is the implementation to extract every individual digit of a number:
C++
#include<bits/stdc++.h>
using namespace std;
void extract( int n){
if (n == 0)
{
return ;
}
extract(n / 10);
cout << n % 10 << endl;
}
int main()
{
extract(1234);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static void extract( int n)
{
if (n == 0 )
{
return ;
}
extract(n / 10 );
System.out.println(n% 10 );
}
public static void main(String[] args)
{
extract( 1234 );
}
}
|
Python3
def extract(n):
if (n = = 0 ):
return
extract(n / / 10 )
print (n % 10 )
if __name__ = = "__main__" :
extract( 1234 )
|
C#
using System;
class GFG{
static void extract( int n)
{
if (n == 0)
{
return ;
}
extract(n / 10);
Console.Write(n % 10 + "\n" );
}
public static void Main(String[] args)
{
extract(1234);
}
}
|
Javascript
<script>
function extract(n)
{
if (parseInt(n) == 0)
{
return ;
}
extract(parseInt(n / 10, 10));
document.write(n % 10 + "</br>" );
}
extract(1001);
</script>
|
Similar to this, various other operations can be performed using recursion. Every iterative function can be computed using the recursion.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!