Recursion
Recursion
— Recursive functions may be less efficient than iterative solutions in — Reduces the length of code and becomes more readable and
terms of memory and performance. understandable to the user/ programmer.
3 4
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
Chapter III : Recursion Chapter III : Recursion
Definition Definition
❑ Features of Recursion ❑ Approach of Recursion
Disadvantages : A recursive function is defined by:
▪ at least one base case and,
— Their execution is occasioned by a considerable loss of time, and ▪ at least one general case.
calls for the use of stacks;This leads to excessive memory usage.
— Basic Case: describes cases where the result of the function is
— Recursive functions can be more challenging to debug and simple to calculate: the value returned by the function is directly
understand than iterative solutions. defined.
— General case: The function is called recursively, and the returned
— Recursion can lead to stack overflow errors if the recursion depth
result is obtained using the result of the recursive call. With each
is too high.
recursive call, the value of at least one of the function’s parameters
must change.
5 6
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
23 24
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
25 26
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
Chapter III : Recursion Chapter III : Recursion
Notion of a function call Notion of a function call
Let be an instruction register (IR) that holds the instruction to be {Calling a Function}
Begin {Start of Main Program}
executed in a given program. {Part before calling func}
…
How does a function call work? Knowing that this called function is x ← 1 The main program has a runtime
y ← 2 context that it must resume when
located in a memory area that is not necessarily adjacent to the r ← func(x)
current instruction. {Part after call to func} the function func gives it back
… control.
To understand this mechanism, let's look at the following abstract x ← r + y
End
algorithm: {Calling a Function}
Begin {Start of Main Program}
{Part before calling func} The variables x and y must have the same values as before the function
…
x ← 1 func was called (if the function func fdoesn't change them).
y ← 2 When calling func(x) the values of x and y
r ← func(x) {Call to func}
{Part after call to func} are saved somewhere and then restored at the end of this call. The
… same goes for any parameters that the main program would have had.
x ← r + y
End
27 28
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
29 30
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
Chapter III : Recursion Chapter III : Recursion
Notion of a function call Notion of a function call
{Execution steps of the main program} If we analyze the order of saving variables before the call and
1. Part before the call to func. restoring them after, we will notice that the variables saved first
2. Save the variables and parameters of the main program. are the last ones to be restored. And those saved last are
3. Pass x to func, and run func. the first ones to be restored.
4.
{Execution steps of func}
a). Part before the call to func2
b). Save local variables and parameters of func.
c). Pass z to func2, and execute func2.
d). Restore local variables and parameters of func.
The principle of a
e). Part after the call to func
STACK
5. Restore the variables and parameters of the main program. →
6. Part after the call to func. →
31 32
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
37 38
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
Chapter III : Recursion Chapter III : Recursion
Converting recursive algorithms to iteratives Converting recursive algorithms to iteratives
❑ Conversion Steps ❑ Conversion Steps
3) On each recursive call
It consists of reproducing the call steps seen previously.
a. Push the current DZ (CDZ) into the stack.
1) Define the DZ: this step involves defining the DZ content of the b. Prepare the call, and a DZ.
recursive function. (Call parameters, local variables, return address). c. Go to the function to run it.
4) After each return
2) Define call and return points : we must define the points (or
a. Retrieve the return address which is in the CDZ.
addresses) where the recursive function is called, and where it must return
b. Pop a DZ (That is to say restore the DZ of calling program).
to the calling program.
c. Connect to the return address retrieved in (a).
39 40
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
41 42
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
Chapter III : Recursion Chapter III : Recursion
Converting recursive algorithms to iteratives Converting recursive algorithms to iteratives
❑ Conversion Example ❑ Conversion Example
Function Fact(n : integer) : integer
2. Define call and return points Var a, f: integer; S : stack; CDZ: DZ
The second step in the conversion process is to define the call and Begin
return points of the recursive function. CreateSrack(S)
We start with the starting point of the function, the trivial case. (The If CDZ.n ← n {Initialize the Current Data zone}
CDZ.adr ← 1 {Final Return Point address}
statement (If (n <= 1)), This specific point of the function is
Start: If (CDZ.n <= 1) Then {starting point}
important, since this is where we have to connect on each call. f ← 1
So let's call this point START. The call point is clear and made explicit by a ← CDZ.adr {Retrieve the return address}
recursive call. Pop(S, CDZ) {Restore the calling subprogram DZ}
As for the return points, we have two: If a = 1 Then {Return handling}
— The final return point, located at the Return f statement, is the return GoTo RP1 {Final Return Point}
point to the calling program. Let's label this point with label “RP2”. Else
— The return point of the recursive call, located just after the recursive GoTo RP2 {Recursive Call Return Point}
call. Let's label this point with label “RP1”.
Dr. Lamia CHEKLAT
43
Dr. Lamia CHEKLAT EndIf … 44
Let's try to improve our solution further. If we look more closely at the Start: If (n <= 1) Then {starting point}
initial recursive solution: The variable x is not used after returning from f ← 1
the call to the Factorial function. So why save it? If IsEmpty(S) Then {Return Management}
Hence, we just need to save and retrieve the variable n. Finaly, the use of GoTo RP1
a simple stack of integers is enough. Else
Pop(S, n) {Restore the calling subprogram DZ}
GoTo RP2
Now let's rewrite a simplified version of the iterative algorithm.
EndIf
…
47
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT 48
53 54
Dr. Lamia CHEKLAT Dr. Lamia CHEKLAT
Chapter III : Recursion Chapter III : Recursion
Converting recursive algorithms to iteratives Converting recursive algorithms to iteratives
❑ Exercice 1: ❑ Exercice 1: Solution
Consider the recursive function PrRec which calculates the sum of the Function PrIT(n: Integer): Integer
Var r : Integer ; S : Stack
squares of the first n numbers. Transform it into an iterative function Begin
(informel version) CreateStack(S)
Function SumSqrRec(n : Integer): Integer x ← n
Start: If ( n = 1) Then
Var r: Integer r ← 1
Begin Else
If ( n = 1 ) Then Push(S, n)
r ← 1 n ← n - 1
Else GoTo START
If (n > 1) Then {to exclude negative n} EndIf
r ← SumSqrRec(n-1) RP2: If IsEmpty(Stack) Then
r ← r + (n*n) Goto RP1
EndIf Else
EndIf Pop(S, n)
Return r r ← (n * n )+ r
End Goto RP2
EndIf
RP1: Return r
Dr. Lamia CHEKLAT
55 End 56