Data Structures: Recursion
Data Structures: Recursion
Recursion
Dr. Seemab
Latif
Lecture No. 12
Todays Lecture
In this lecture we will:
study recursion. Recursion is a
programming technique in which
procedures and functions call
themselves.
look at the stack a structure
maintained by each program at run
time.
2
Introduction
in
which
Recursive Definition
A
Example 1
X *
X *X * X * X
*....*X
N times
X * X *
X *X* X
*
....
*X
( N 1) _ times
Also as
X * X * X *
X * X *
.....
*
X
( N 2 ) _ times
X *X
N 1
6
34
34 3 * 33
33 3 * 32
32 3 * 31
x , int
//Base
31 3
definition
calculate factorial of n
Base case
If n = 0, return 1
Recursive step
Calculate the factorial of n-1
Return n (the factorial of n-1)
10
Recursive Programming
main
factorial(3)
return 6
factorial(3)
3 * factorial(2)
return 2
factorial(2)
2*factorial(1)
return 1
factorial(1)
1*factorial(0)
return 1
factorial(0)
12
Another Example--1
Here is a function to
print all the elements of
a linked list.
getFromList()extracts
one item from the head
of the list and than
return the its value. In
addition, it also return a
new pointer pointing to
rest of the list NOT
include the returned
item.
printAll()displays on the
console ALL the items
stored in the entire
linked list. It terminates
Another Example--2
The
14
Visualization
15
Brain Storming!!!
Printing
It
It
18
Recursion: Final
Remarks
The
19
Exercise
The problem of computing the sum of all the
numbers between 1 and any positive integer N
can be recursively defined as:
N
N-1
=
i=1
N-2
=
i=1
N + (N-1) +
i=1
etc.
20
Exercise
int sum(int n)
{
if(n==1)
return n;
else
return n + sum(n-1);
}
21