Table of contents
No headings in the article.
We all heard about DSA and its need. In DSA we come across a topic known as "Recursion" and Today I will give a brief intro of it to you. So recursion in basic words is "calling itself". So in a function when we call the same function in itself, This condition is called Recursion.
Let's take an example:
In this, I have taken a code for factorial. Let's see the code below:
int factorial(int n){
if(n == 0 ){
return 1;
}
int smalloutput = factorial(n-1);
int output = n * smalloutput;
return output;
}
So analyzing this code :
Firstly, a function will be declared, here it is named factorial in which we pass int n as an argument.
So let's deep dive into this, and remember the topic we study in mathematics known as the Principle of Mathematical induction. In the concept, we take a base case and then an inductive case. So in this code, as the base code I have defined if n is equal to zero then return 1 as 0!=1. After this, we assume that at n-1 the statement holds true (2nd statement of PMI). We will take a variable output in which we will store the value of n*smallOutput where smallOutput is the factorial of n-1 terms. And Lastly, we will return the value of the output.
Let's now print the code :
#include<iostream>
using namespace std;
int factorial(int n){
if(n == 0 ){
return 1;
}
int smalloutput = factorial(n-1);
int output = n * smalloutput;
return output;
}
int main(){
int n;
cin>> n;
cout << factorial(n) << endl;
}
The output of the code will be:
Reading it for the first time can be overwhelming but it will come as easy when we move forward. So chill learn it steadily and easily. Be consistent and if u like it make sure to follow me and also drop suggestions.
Thanks,
Yash