The difference between recursion and iteration
Recursion:
1) recursion is the invocation of itself within a procedure or function;
2) When using recursion, there must be a definite recursive end condition called a recursive exit.
Iteration:
Use the original value of the variable to derive a new value for the variable. If recursion calls itself, the iteration is a non-stop call to B.
1, Fibonacci 1 1 2 3 5 8
Recursive algorithm
def fibo1 (N)
If N==1 or n==2
return 1;
End
Fibo1 (n-1) +fibo1 (n-2)
End
Puts Fibo1 (6);
Tail recursion, which takes each result into the next operation, much like the iteration.
def Fibo2 (N,g,k)
Puts K
A=k
K=g+k
G=a
If N==1
Return K
End
Fibo2 (N-1,g,k)
End
Puts Fibo2 (5,0,1)
Iteration
def FIBO3 (N)
j,k=0,1
Puts J
Puts K
For I in 1..N
A=k
K=j+k
J=a
Puts K
End
End
2. Factorial
Tail recursion
def fact (N,g)
If n==0
return g;
End
Fact (N-1,N*G)
End
ruby-recursion and tail recursion