Recursive FN
Recursive FN
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.
2
RECURSIVE ALGORITHMS
Recursive algorithms
Algorithm:
Algorithm Factorial(n)
Begin
End
3
WHAT IS A RECURSIVE
FUNCTION?
A recursive function is often defined as “a function that calls itself.”
4
EXAMPLE: FACTORIAL
Problem:
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
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