(DS&A) Recursion
(DS&A) Recursion
❖ Recursive Case:
✓ In addition to the base case, recursive functions have a recursive case.
✓ The recursive case defines how the function calls itself with modified
parameters.
✓ Each recursive call should move closer to the base case, ensuring
termination.
❖ Lets write a function factorial (n) which takes a positive a positive
integer as its argument and returns the n𝑡ℎ factorial.
✓ n! = n*(n-1)*(n-2)…3*2*1, This can be rewritten as:-
✓ n!=n.(n-1)!.
✓ But this is not complete definition of factorials because there are cases
where this definition is not applicable.
➢ 2!=2*1!=2.
➢ 1!=1*0=0.
➢ But when you get to 0 there will be a problem,
➢ 0!=0*(-1)! and -1! Is not defined .
➢ Therefore n! = n. (n-1)! Works only for n ≥ 1.
➢ This leads to creation of two separate cases:-
n!= n*(n-1)! if n≥ 1
1 if n=0
int recursiveFactorial(int n)
{
if (n>=1)
{
return n* recursiveFactorial(n-1);
}
else
{
return 1;
}
}
Cont.…
❖ Example:-
Cont.…
✓ factorial(4)-> 4*factorial(3).
✓ factorial(3)-> 3*factorial(2).
✓ factorial(2)-> 2*factorial(1).
✓ factorial(1)-> 1*factorial(0).
✓ factorial(0)-> 1.
❖ E.g. 112358
❖ Lets write a function fib(n) that returns the n𝑡ℎ number in the
sequence.
❖ Firstwe need to formally define the relation between different
Fibonacci numbers:-
❖Fn=Fn-1+ Fn-2
❖ Fn= the n𝑡ℎ Fibonacci number.
❖ 112358
❖ F5 = F4+ F3=5.
❖ The equation Fn=Fn-1+ Fn-2 is correct most of the time , but it is not
complete .
❖ E.g. if you plug in 5 to n the equation holds true ,but if you plug in 2 for n.
❖ F2=F1+ F0 , F0 is not defined, this case also happens when plugging in 1
for n.
❖ To accommodate this changes we rewrite the equation as follows:
Fn= Fn-1+ Fn-2 if n≥ 3
1 if n=1 or n=2
int fib(int n)
{
if (n>=3)
{
return fib(n-1)+fib(n-2);
}
else
{
return 1;
}
}
❖ Both iteration and recursion are based on control structure.
❖ Iteration uses a repetition structure (such as for, while, do…while)
and recursive uses a selection structure (if, if else or switch).
❖ Both iteration and recursive can execute infinitely.
❖ Infinite loop occurs with iteration if the loop continuation test
become false and infinite recursion occurs if the recursion step
doesn’t reduce the problem in a manner that coverage on a base
case.
❖ Recursion has a disadvantage. It repeatedly invokes the mechanism,
and consequently the overhead of method calls.
❖ This can be costly in both processor time and memory space. Each
recursive call creates another copy of the method (actually, only the
function’s variables); this consumes considerable memory.
❖ Use recursion if:-
✓ A recursive solution is natural and easy to understand.
✓ A recursive solution doesn’t result in excessive duplicate computation.
✓ The equivalent iterative solution is too complex .