SlideShare a Scribd company logo
2
Most read
4
Most read
17
Most read
Recursion
Difference between recursion and iteration
based functions
 Recursion uses selection structure.
 Infinite recursion occurs if the recursion step does not reduce the problem in a
manner that converges on some condition (base case) and Infinite recursion can
crash the system.
 Recursion terminates when a base case is recognized.
 Recursion is usually slower than iteration due to the overhead of maintaining the
stack.
 Recursion uses more memory than iteration.
 Recursion makes the code smaller.
continued
 Iteration uses repetition structure.
 An infinite loop occurs with iteration if the loop condition test never becomes false
and Infinite looping uses CPU cycles repeatedly.
 An iteration terminates when the loop condition fails.
 An iteration does not use the stack so it's faster than recursion.
 Iteration consumes less memory.
 Iteration makes the code longer.
Definition
Recursion is one of the most powerful
tool in a proramming language.Recursion
is a way of proramming where function
calls itself again and again.Recursion is
defined as defining something in terms
of itself.
Recursion Essentials
 There must be terminating condition for the problem,
 There must be an if condition in the recursive routine.This if clause specifies the
terminatin condition for the recursion.
 Reversal in te order of execution is the characteristics of every recursive problem.wen a
recursive program is taken for execution , the recursive function calls are not executed
immidiately.They are pushed on the stack as long as terminating condition is
encountered. Asoon as recursive condition is encountered the recursive calls which were
pushed on to stack are removed in reverse order and executed one by one.It means that
last call made would execute first,then the second last call will execute and so on till the
stack is empty.
 Each time a new recursive call is made new memory space will be allocated to each local
variableused by the recursive routine.In oter words during each recursive call to
recursive function the local variables of recursive functions gets a different set of values
but withh the same name.
Contd...
 The duplicated values of a local variables of a recursive calls are pushed on to stack
with its respective calls all there values are available to the respective calls when it
is popped off from the stack.
Disadvantages:it consumes more storage space between the recursive calls along with
local variables are stored on the stack.
The computer may run out of memory if recursive calls are not checked.
It is less efficient in terms of memory and execution speed.
So dividing the recursive problem into two parts:terminating part and recursive part.
Examples
def power(x,n):
if(n==0):
return 1
else:
return(x*power(x,n-1))
a=2
print(power(a,4))
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
Continued...
def recur_factorial(n):
if (n == 1):
return n
else:
return n*recur_factorial(n-1)
num = 5
# check if the number is negative
if (num < 0):
print("Sorry, factorial does not exist for negative numbers")
elif (num == 0):
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Continued...
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# take input from the user
nterms = int(input("How many terms? "))
# check if the number of terms is valid
if (nterms <= 0):
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Continued...
def hcf(a,b):
if b==0:
return a
else:
return hcf(b, a%b)
# this is recursion as hcf() calls itself
# Reading numbers from user
first = int(input('Enter first number: '))
second = int(input('Enter second number: '))
# Function call & displaying output HCF (GCD)
print('HCF or GCD of %d and %d is %d' %(first, second, hcf(first, second)))
Activation record
An activation record usually contains the following information:
1. values for all parameters in the function
2. local variables which can be stored elsewhere
3. Return address to resume control by the caller,the address of the callers
instruction immidiately following the call
4. A dynamic link,which is a link to the callers activation record.
5. The returned value of a function.
Module
Modular programming is a software design technique to split your code into separate parts. These parts are called modules. The focus for
this separation should be to have modules with no or just few dependencies upon other modules. In other words: Minimization of
dependencies is the goal.
If you want to develop programs which are readable, reliable and maintainable without too much effort, you have to use some kind of
modular software design. Especially if your application has a certain size.
A1.py
def greeting(name):
print("Hello, " + name)
import A1
A1.greeting("JAIRAM")
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
A1.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
import A1
a = A1.person1["age"]
print(a)
Lambda function
A lambda function is a small anonymous function.A lambda function can take any
number of arguments, but can only have one expression.
lambda arguments : expression
x = lambda b : b + 10
print(x(7))
x = lambda a, b : a *b
print(x(4, 6))
x = lambda a, b, c : a + b + c
print(x(3, 3, 2))
Pass statement
 The pass statement is a null statement. But the difference between pass and comment is that
comment is ignored by the interpreter whereas pass is not ignroed.
 The pass statement is generally used as a placeholder i.e. when the user does not know what code
to write.
 user simply places pass at that line. Sometimes, pass is used when the user doesn’t want any code
to execute.
 user simply places pass there as empty code is not allowed in loops, function definitions, class
definitions, or in if statements.
 using pass statement user avoids this error.
l =[‘u', ‘g', ‘j', ‘d']
for i in l:
if(i ==‘u'):
pass
else:
print(i)

More Related Content

PDF
Python recursion
PPTX
lecture4-recursion.pptx
PPTX
Recursion-in-Python for class third.pptx
PDF
Python Programming unit5 (1).pdf
PDF
14. Recursion.pdf
PPTX
Recursion
PPTX
Python Session - 4
PPTX
Full_Fixed_Enhanced_Recursion_Presentation.pptx
Python recursion
lecture4-recursion.pptx
Recursion-in-Python for class third.pptx
Python Programming unit5 (1).pdf
14. Recursion.pdf
Recursion
Python Session - 4
Full_Fixed_Enhanced_Recursion_Presentation.pptx

Similar to Recursion vs. Iteration: Code Efficiency & Structure (20)

PDF
Chapter 7 recursion handouts with notes
PPTX
Recursive Algorithms with their types and implementation
PDF
Recursion For the Rest of Us (CS Fundamentals Series)
PPTX
Introduction to python programming ( part-2 )
PPTX
Unit-I Recursion.pptx
PPTX
Python recursion
PPTX
6 Recursion Using Python 1.pptx6 Recursion Using Python 1.pptx
PPTX
McMullen_ProgwPython_1e_mod12_PowerPoint.pptx
PPT
Data Structures- Part5 recursion
DOCX
Python unit 3 and Unit 4
PPTX
Enhanced_Recursion_Presennnnntation.pptx
PPT
recursion.ppt
PPTX
Python-Functions.pptx
PPTX
Recursion and Sorting Algorithms
PPTX
Chapter 02 functions -class xii
PPTX
Recursion is used in programming languages to use a procedure multiple times ...
PPT
Recursion and looping
PPTX
Recursion in Data Structure
PDF
Recursion in Python.pdf
PPTX
DSA. Data structure algorithm dRecursion.pptx
Chapter 7 recursion handouts with notes
Recursive Algorithms with their types and implementation
Recursion For the Rest of Us (CS Fundamentals Series)
Introduction to python programming ( part-2 )
Unit-I Recursion.pptx
Python recursion
6 Recursion Using Python 1.pptx6 Recursion Using Python 1.pptx
McMullen_ProgwPython_1e_mod12_PowerPoint.pptx
Data Structures- Part5 recursion
Python unit 3 and Unit 4
Enhanced_Recursion_Presennnnntation.pptx
recursion.ppt
Python-Functions.pptx
Recursion and Sorting Algorithms
Chapter 02 functions -class xii
Recursion is used in programming languages to use a procedure multiple times ...
Recursion and looping
Recursion in Data Structure
Recursion in Python.pdf
DSA. Data structure algorithm dRecursion.pptx
Ad

Recently uploaded (20)

PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
ai tools demonstartion for schools and inter college
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Digital Strategies for Manufacturing Companies
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Introduction to Artificial Intelligence
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Understanding Forklifts - TECH EHS Solution
PDF
top salesforce developer skills in 2025.pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
history of c programming in notes for students .pptx
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Reimagine Home Health with the Power of Agentic AI​
Design an Analysis of Algorithms I-SECS-1021-03
ai tools demonstartion for schools and inter college
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
VVF-Customer-Presentation2025-Ver1.9.pptx
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Digital Strategies for Manufacturing Companies
How to Choose the Right IT Partner for Your Business in Malaysia
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Introduction to Artificial Intelligence
Internet Downloader Manager (IDM) Crack 6.42 Build 41
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Understanding Forklifts - TECH EHS Solution
top salesforce developer skills in 2025.pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
history of c programming in notes for students .pptx
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Ad

Recursion vs. Iteration: Code Efficiency & Structure

  • 2. Difference between recursion and iteration based functions  Recursion uses selection structure.  Infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on some condition (base case) and Infinite recursion can crash the system.  Recursion terminates when a base case is recognized.  Recursion is usually slower than iteration due to the overhead of maintaining the stack.  Recursion uses more memory than iteration.  Recursion makes the code smaller.
  • 3. continued  Iteration uses repetition structure.  An infinite loop occurs with iteration if the loop condition test never becomes false and Infinite looping uses CPU cycles repeatedly.  An iteration terminates when the loop condition fails.  An iteration does not use the stack so it's faster than recursion.  Iteration consumes less memory.  Iteration makes the code longer.
  • 4. Definition Recursion is one of the most powerful tool in a proramming language.Recursion is a way of proramming where function calls itself again and again.Recursion is defined as defining something in terms of itself.
  • 5. Recursion Essentials  There must be terminating condition for the problem,  There must be an if condition in the recursive routine.This if clause specifies the terminatin condition for the recursion.  Reversal in te order of execution is the characteristics of every recursive problem.wen a recursive program is taken for execution , the recursive function calls are not executed immidiately.They are pushed on the stack as long as terminating condition is encountered. Asoon as recursive condition is encountered the recursive calls which were pushed on to stack are removed in reverse order and executed one by one.It means that last call made would execute first,then the second last call will execute and so on till the stack is empty.  Each time a new recursive call is made new memory space will be allocated to each local variableused by the recursive routine.In oter words during each recursive call to recursive function the local variables of recursive functions gets a different set of values but withh the same name.
  • 6. Contd...  The duplicated values of a local variables of a recursive calls are pushed on to stack with its respective calls all there values are available to the respective calls when it is popped off from the stack. Disadvantages:it consumes more storage space between the recursive calls along with local variables are stored on the stack. The computer may run out of memory if recursive calls are not checked. It is less efficient in terms of memory and execution speed. So dividing the recursive problem into two parts:terminating part and recursive part.
  • 11. Continued... def recur_factorial(n): if (n == 1): return n else: return n*recur_factorial(n-1) num = 5 # check if the number is negative if (num < 0): print("Sorry, factorial does not exist for negative numbers") elif (num == 0): print("The factorial of 0 is 1") else: print("The factorial of", num, "is", recur_factorial(num))
  • 12. Continued... def recur_fibo(n): if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) # take input from the user nterms = int(input("How many terms? ")) # check if the number of terms is valid if (nterms <= 0): print("Plese enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(recur_fibo(i))
  • 13. Continued... def hcf(a,b): if b==0: return a else: return hcf(b, a%b) # this is recursion as hcf() calls itself # Reading numbers from user first = int(input('Enter first number: ')) second = int(input('Enter second number: ')) # Function call & displaying output HCF (GCD) print('HCF or GCD of %d and %d is %d' %(first, second, hcf(first, second)))
  • 14. Activation record An activation record usually contains the following information: 1. values for all parameters in the function 2. local variables which can be stored elsewhere 3. Return address to resume control by the caller,the address of the callers instruction immidiately following the call 4. A dynamic link,which is a link to the callers activation record. 5. The returned value of a function.
  • 15. Module Modular programming is a software design technique to split your code into separate parts. These parts are called modules. The focus for this separation should be to have modules with no or just few dependencies upon other modules. In other words: Minimization of dependencies is the goal. If you want to develop programs which are readable, reliable and maintainable without too much effort, you have to use some kind of modular software design. Especially if your application has a certain size. A1.py def greeting(name): print("Hello, " + name) import A1 A1.greeting("JAIRAM") The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc): A1.py person1 = { "name": "John", "age": 36, "country": "Norway" } import A1 a = A1.person1["age"] print(a)
  • 16. Lambda function A lambda function is a small anonymous function.A lambda function can take any number of arguments, but can only have one expression. lambda arguments : expression x = lambda b : b + 10 print(x(7)) x = lambda a, b : a *b print(x(4, 6)) x = lambda a, b, c : a + b + c print(x(3, 3, 2))
  • 17. Pass statement  The pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignroed.  The pass statement is generally used as a placeholder i.e. when the user does not know what code to write.  user simply places pass at that line. Sometimes, pass is used when the user doesn’t want any code to execute.  user simply places pass there as empty code is not allowed in loops, function definitions, class definitions, or in if statements.  using pass statement user avoids this error. l =[‘u', ‘g', ‘j', ‘d'] for i in l: if(i ==‘u'): pass else: print(i)