+ 2
How exactly the recursive function work?? Explain me with real time example
3 Answers
+ 5
recursion is calling the a function within itself. this is used to prevent sloppy brutal code and to prevent using loops.
The most simple example is with factorial recursion.(!)
public int fact(int n) {
if(n==1) return 1;
else return n*fact(n-1);
}
System.out.println(fact(4));
output: 24
Explanation:
The code runs at the start with 4.
4 is larger then 1 then is returns 4*fact(4-1)
then it runs fact(3)
3>1 ; returns 3*fact(3-1)
2>1; returns 2*fact(2-1)
1=1; returns 1.
then the whole function is solved.
2*fact(2-1)=2 = fact(2)
3*fact(2) = 6 = fact(3)
4*fact(3)= 24 = fact(4)
+ 4
Some examples and discussion on recursive functions:
https://www.sololearn.com/Discuss/1111022/?ref=app
+ 2
https://code.sololearn.com/W5oKwh4eGFDQ/?ref=app
My favorite example of recursive function has always been a fractal tree. in this code, notice a function called
doit()
inside that function, it draws a line from point A to point B.. At the end of the function, it calls the function 2 times with point B as the starting point.
Since it calls this function twice, it draws 2 lines from point B to points C and points D.
Each of runs of the function calls the function 2 more times. so it goes from C and D to E,F,G,H.. and repeats until told not to.
call function and it draws a line..
|
Then it calls itself twice and draws those lines..
\/
|
And so on
\ / \/
\/
|