0
How recursion us work?
What is use of recursion and how it works???
2 Réponses
+ 2
- recursion is like the loops you learnt
- there are two conditions needed the limit/base and the general condition
- the base marks for the start and stop
- and the general conditions for what it is supposed to do eg: keep adding till a certain limit , finding factorial etc
0
recursion is when you call a function inside itself
let's take for example factorial :
factorial(1) = 1
factorial(n) = n × factorial(n-1)
this is the implementation in c :
int factorial(int n){
if(n==1) return 1;
else return n*factorial(n-1);
}
let's take n=3 and call factorial(3)
first : 3 * factorial(2)
second: 3 * 2 *factorial(1)
last: 3 * 2 * 1 wich equals to 6
3! = 6
sometimes you find yourself forced to use a recursion because it's impossible to use a loop .
recursion generally is faster in execution but consumes lot of memory
hope this explains it to you