RECURSION
FUNCTIONS
1
MOTIVATION - RECURSION
Almost all computation involves the repetition of steps.
Iterative control statements, such as the for and while statements, provide
one means of controlling the repeated execution of instructions.
Another way is by the use of recursion.
In recursive problem solving, a problem is repeatedly broken down into
similar sub problems, until the sub problems can be directly solved without
further breakdown.
2
RECURSIVE ALGORITHMS
Recursive algorithms
The functions computed by the algorithms are expressed in terms of itself
Example: Find the Factorial of a positive integer
Algorithm:
Algorithm Factorial(n)
Begin
if (n=1) than return 1
else return(n * Factorial(n-1))
End
3
WHAT IS A RECURSIVE
FUNCTION?
A recursive function is often defined as “a function that calls itself.”
4
EXAMPLE: FACTORIAL
Problem:
The factorial function is an often-used example of the use of recursion. The
computation of the factorial of 4 is given as,
factorial(4) = 4 * 3 * 2* 1= 24
In general, the computation of the factorial of any (positive, nonzero)
integer n is,
factorial(n) = n . (n-1). (n-2) . . . 1
The one exception is the factorial of 0, defined to be 1.
5
LOGIC
The factorial of n can be defined as n times the factorial of n – 1
6
A RECURSIVE FACTORIAL
FUNCTION IMPLEMENTATION
Input
factorial(4)
7
FACTORIAL RECURSIVE
INSTANCE CALLS
8
9
EXAMPLES
Python Program to Find the Fibonacci Series Using Recursion
10
ADVANTAGE OF RECURSIVE
•Simplified Code for Complex Problems: (e.g.,
quicksort, mergesort).
•Reduced Use of Loops.
•Breaks Down Problems Naturally.
•Code Reusability.
•Easier State Management: In recursion, each
recursive call can manage its own state (local
variables and scope).
11
DIS-ADVANTAGE OF
RECURSIVE
High Memory Usage
Call Stack Overhead
Stack Overflow
Slower Execution Compared to Iteration
Complex Debugging and Testing
Can Be Less Intuitive for Non-Trivial Problems(Difficult to Understand and
Maintain For some complex problems)
Performance Issues with Overlapping Subproblems
Limited Use Cases in Practice(Not Always the Best Fit)
12
EXAMPLES
Python Program to Find the Sum of the Digits of the Number Recursively
Python Program to Check Whether a String is a Palindrome or not Using
Recursion
Python Program to Reverse a String Using Recursion
Python Program to Find if a Number is Prime or Not Prime Using Recursion
13
MORE EXAMPLES ON
FUNCTIONS
Write a Python function that takes a list and returns a new list with unique
elements of the first list.
Write a Python function to check whether a number is perfect or not.
Write a Python function that that prints out the first n rows of Pascal's
triangle.
Write a Python function to check whether a string is a pangram or not. (A
pangram is a sentence containing every letter in the English Alphabet.)
Write a Python function to create and print a list where the values are
square root of numbers between lower and higher ranges (both included).
14
SAMPLE
PASCAL
'S
TRIANG
LE
15