Recursion
Recursion
Department: Mathematics
LAOUICI.Z
1
Recursion
number 1
Recursion
4
Recursion
Definition
Recursion is the process in which a function calls itself directly or
indirectly
A Mathematical Interpretation: the sum of first n natural numbers
Slide /6
Recursion : Execution trace
(progression)
Example 1 <
Function Fact(n: int):int;
Variable i, f : int;
Factorial>
Begin
if (n <=1)then Return (1);
else
Return (n * Fact(n-1)) ;
Endif ;
End
0! = 1! = 1 {base case}
n! = n*(n-1)*…*1 = n * (n-1)!
7
Recursion : Execution trace
(progression) Example <
Fact(4) Descent Factorial>
Function Fact(n: int):int;
Variable i, f : int;
phase Begin
24 if (n <=1)then Return (1);
4 * Fact(3) else
Return (n * Fact(n-1)) ;
Endif ;
6 End
3 * Fact(2)
2
2 * Fact(1)
1
8
Recursion : Execution trace
(progression) .
Example 2
Mathematical Equation:
if n == 0, n == 1;
fib(n) = fib(n-1) + fib(n-2) otherwise;
Recurrence Relation:
T(n) = T(n-1) + T(n-2)
Slide /9
Recursion : Execution trace
(progression)
Example <
Fibonacci>
Fib(4) 3
Function Fib(n: int):int;
Variable i, f : int;
2 Fib(3) + Fib(2)
Begin 1
if (n =0)then Return (0);
1 Fib(2) + Fib(1) 1 else
Fib(1)+ Fib(0)
if (n =1)then Return (1);
1else 0
Fib(1)+ Fib(0) Return (Fib(n-1)+ Fib(n-
2));
1 0 Endif ;
Endif ;
End;
Recursion : Exercises
Exercise
1. Write a recursive function that calculates the sum of two natural numbers, a and b.
a + b
5 + 4 5 +(1+1+1+1) if(b=0) => Sum = a +0 =a => 5
Exercise
Let T be an array of integers of size n (n ≤ 100). Write recursive functions to perform the
following operations:
1. Prod: which returns the product of the elements of array T.
13
Prod: which returns the product of the
elements of array T. T 5 2 3 1 n
Product of subarray *
(T ,size n-3) Prod (T ,n-3) = T[n-1]= T[1]= 2
Product of subarray *
T[n-1]= T[0]= 5
(T ,size n-4 = 4-4=0)
If there are no elements in the vector
Prod (T ,n-4) Prod (T ,0)=1
* n=0<nbr of element =0> => prod =1
14
Recursion : Exercises
15
Recursion : Exercises
Exercise
Let T be an array of integers of size n (n ≤ 100). Write recursive functions to perform the
following operations:
1. Prod: which returns the product of the elements of array T.
2. sorted: which indicates whether this array is sorted in ascending order or not
16
sorted: which indicates whether this array is
sorted in ascending order or not T 1 4 6 9 n
Sorted =vrai
Sorted(T ,n) =
The result is at the level of the T[n]> T[n-1]
subarray (T with size n-1).
Sorted(T ,n-1) = T[3]> T[2]=9>6
The result is at the level of the
subarray (T with size n-2).
Sorted(T ,n-2) = T[n-1]> T[n-2]
T[2]> T[1]=6>4
The result is at the level of the
Sorted(T ,n-3) T[n-2] > T[n-3]
subarray (T with size n-3).
= T[1]> T[0]=4>1
Sorted(T ,n-4) Sorted(T ,0)=True
If there is only one element in the
17
array,. n=0 => Sorted=True
Recursion : Exercises
19