+ 1
What is the imortant of recursion on coding?
What is the uses and important in recursion in codding??
4 Réponses
+ 3
Explaining with functions. A recursive function is a function that calls itself. It has a base case and a recursive case. A simple example is factorial.
4! = 4 * 3! = 4 * 3 * 2! = 4 * 3 * 2 * 1! = 4 * 3 * 2 * 1 = 24
Idk java very well but I'll write an algorithm (pseudo-python):
fact(n)
if n == 0 or n == 1
stop recursion and return 1
else
return n * fact(n - 1)
If you follow the lines starting with fact(3), you will have 3 * fact(2), it is 3 * 2 * fact(1), this is 3 * 2 * 1 and it ends and returns 6 = 3!
Base case and recursive case are the most important part :)
+ 2
imagine u have to calculate fibonacci sequence for example (i'll do it in python)
By definition
fib(0) = 0
fib(1) = 1
fib (n) = fib(n-1) + fib(n-2)
the code would be
def fib(n):
if n <= 1: return n
return fib(n-1) + fib(n-2)
use recursion when u dont know how to making something using pure loops
+ 1
I know its a mega loop but can someone explain more?
- 1
https://code.sololearn.com/cQZ3qUkqPAzF/?ref=app
This might help you understand the power of recursion.