Data Structures & Algorithms: Lecture 7: Stack & Recursion
Data Structures & Algorithms: Lecture 7: Stack & Recursion
04/11/2020
Today‘s lecture
▪ Stacks
► Practical applications
▪ Recursive algorithm
► Algorithm that finds the solution to a given problem by
reducing the problem to smaller versions of itself
► Has one or more base cases
▪ Recursive function
► Function that calls itself
▪ Base case
► Case in recursive definition in which the solution is
obtained directly
► Stops the recursion
▪ General case
► Case in recursive definition in which a smaller version of
itself is called
► Must eventually be reduced to a base case
if (answer is known)
Base case
provide the answer
else
make a recursive call to Recursive case
solve a smaller version
of the same problem
▪ Recursive function
► May have unlimited copies of itself
► Every recursive call has
4! = 4 * 3 * 2 * 1
n! = n * (n-1) * … * 1
4! = 4 * 3!
n! = n * (n-1)!
1 𝑖𝑓𝑛 = 0
n! =
𝑛∗ 𝑛−1 ! 𝑖𝑓 𝑛 > 0
0 𝑓𝑜𝑟 𝑛 == 0
𝑓𝑖𝑏 𝑛 = ൞ 1 𝑓𝑜𝑟 𝑛 == 1
𝑓𝑖𝑏 𝑛 − 2 + 𝑓𝑖𝑏 𝑛 − 1 𝑓𝑜𝑟 𝑛 > 2
int main()
{ ...
y = power(5.6,2); /* 136 */
...
}
M. Shahzad: Data Structures & Algorithms Lecture 7: Stack & Recursion 28
First, the value of the second argument, i.e., 2, is checked,
and power() tries to return the value of 5.6 * power(5.6,1)