Difference Between Recursion and Iteration

Difference Between Recursion and Iteration

5 mins read1.8K Views Comment
Updated on Jun 14, 2024 14:49 IST

Recursion is a technique in which the function calls itself in its body to solve the problem, typically breaking into smaller and more manageable sub-problems. In contrast, iteration is a technique that repetitively executes a code block until the condition is unmet. This article will briefly discuss the difference between recursion and iteration.

2023_06_Feature-Image-Templates-50.jpg

Recursion and Iteration are two important concepts of programming where we need to repetitively do certain operations until the given condition is not met. In recursion, the function calls itself in its body to solve the problem, typically breaking into smaller and more manageable sub-problems. In contrast, Iteration is a technique that repetitively executes a code block until the condition is unmet.

Both are used where we need repetition of certain operations, but both are different in the Control Structure, Space Complexity, Performance, etc. 

What is Programming What is Python
What is Data Science What is Machine Learning

In this article, we will learn how these two major programming concepts differ based on different parameters. And later in the article, we will take some examples to understand these concepts better.

So, let’s start with the tabular difference between Recursion and Iteration.

Table of Content

Recommended online courses

Best-suited Programming courses for you

Learn Programming with these high-rated online courses

– / –
6 weeks
10 K
3 months
19.99 K
97 days
– / –
40 hours
4 K
2 months
15 K
3 months
– / –
170 hours
– / –
5 days
– / –
6 months

What is the Difference Between Recursion and Iteration?

  Recursion Iteration
Definition A technique in which the function calls itself in its body to solve the problem, typically breaking into smaller and more manageable sub-problems. Iteration is a technique that repetitively executes a code block until the condition is unmet.
Syntax There is a termination condition specified. The iteration format includes initialization, condition, and increment/decrement of a variable.
Control Structure Function call stack Looping Constructs (for, while etc.)
Problem-Solving Approach Divide and Conquer Sequential Execution
Time Complexity Higher due to the overhead of maintaining the function call stack. Lower than recursion due to the absence of the overhead of function calls.
Space Complexity Higher than iteration. Generally lower than recursion due to the absence of the overhead function calls.
Memory Uses more memory Uses less memory
Speed Slower than Iteration Faster than Recursion as it uses less memory
Application For Functions For Loops
Usage Tree/Graph Traversal or the problem that can be broken down into similar sub-problems Preferred when tasks require repetition of similar tasks over elements in a structure (example, list).

Your Career Awaits: Discover the Best Government Job-Oriented Courses After 10 & Online Government Certification Opportunities

What is Recursion?

Recursion in programming is a method where the solution to a problem depends on solutions to smaller instances of the same problem. Essentially, a recursive function is a function that calls itself during its execution. This enables the function to be repeated several times, as it can call itself during its execution.

Now, let’s have a look at some examples to get a better idea of recursion.

Examples of Recursion

Ques-1: Calculate Fibonacci Series


 
def fibonacci(n):
# Base case
if n <= 1:
return n
# Recursive case
else:
return fibonacci(n-1) + fibonacci(n-2)
# Testing
print(fibonacci(10))
Copy code
2023_06_recursion-example-1.jpg

Ques-2: Tower of Hanoi


 
def hanoi(n, source, target, auxiliary):
if n > 0:
# Move n - 1 disks from source to auxiliary, so they are out of the way
hanoi(n - 1, source, auxiliary, target)
# Move the nth disk from source to target
print('Move disk', n, 'from', source, 'to', target)
# Move the n - 1 disks that we left on auxiliary to target
hanoi(n - 1, auxiliary, target, source)
# Testing
hanoi(3, 'A', 'C', 'B')
Copy code
2023_06_tower-of-hanoi-2.jpg
Types of Recursion in C 
Master the Concept of Recursion Java
Recursion in C++
Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications

What is Iteration?

Iteration in programming is a process wherein a set of instructions or structures are repeatedly executed until some condition is met. We often use loops for iteration in Python, such as the for and while loops.

Now, let’s have a look at some examples to get a better idea of iteration.

Example of Iteration

Ques-1: Find all Prime Number up to a given number.


 
def primes_up_to(n):
"""
Function to calculate all prime numbers up to a given number.
:param n: the upper limit number
:return: a list of prime numbers
"""
primes = []
for potential_prime in range(2, n):
is_prime = True
for num in range(2, potential_prime):
if potential_prime % num == 0:
is_prime = False
if is_prime:
primes.append(potential_prime)
return primes
print(primes_up_to(100))
Copy code
2023_06_example-iteration-1.jpg

Ques-2: Calculate the Factorial of a given number.


 
def factorial(n):
"""
Function to calculate the factorial of a given number.
:param n: the input number
:return: factorial of the input number
"""
result = 1
for i in range(1, n+1):
result *= i
return result
print(factorial(5))
Copy code
2023_06_example-iteration-2.jpg

Ques-3: Find all the occurrence of a substring in a string?


 
def find_substring(string, substring):
"""
Function to find all occurrences of a substring in a string.
:param string: the input string
:param substring: the substring to be found
:return: a list of indexes where the substring starts in the string
"""
indexes = []
index = string.find(substring)
while index != -1:
indexes.append(index)
index = string.find(substring, index + 1)
return indexes
print(find_substring('This is a test. This is only a test.', 'test'))
Copy code
2023_06_example-iteration-3-1.jpg
Introduction to Recursion Functions in Python
Python Continue Statement: How to Skip Iterations and Streamline Code Execution
Python Continue Statement: How to Skip Iterations and Streamline Code Execution
Streamline your Python code by skipping unnecessary iterations using the “continue” statement. Our tutorial explains the syntax and usage of the “continue” statement. It provides examples to help you understand...read more

Key Differences Between Recursion and Iteration?

  • Recursion is a technique in which the function calls itself in its body to solve the problem, typically breaking into smaller and more manageable sub-problems. In contrast, Iteration is a technique that repetitively executes a code block until the condition is unmet.
  • Recursion follows the divide and conquers approach, while Iteration follows the sequential execution approach to solve the problem.
  • The time complexity of recursion is higher than Iteration due to the overhead of maintaining the function call stack.
  • Iteration is faster than recursion due to less memory usage.
  • Iteration is preferred for loops, while recursion is used for functions.

Conclusion

Recursion and Iteration are two important concepts of programming where we need to repetitively do certain operations until the given condition is not met. In this article, we have briefly discussed what is Recursion, what is Iteration with the help of examples and later in the we have also discussed the key differences between recursion and iteration.

Hope you will like the article.

Related Reads:

How to Check Disk Space in Linux?
Understanding splitlines() Function in Python
Password Generator in Python
What are Methods in Python?
The Ultimate Singleton Class Guide: Boost Your Java Code Efficiency Today
What is Polymorphism in C++
Understanding Strerror() Function in C
Understanding Memset() in C++
Exploring Python Pickle: The Ultimate Resource for Object Serialization and Storage

FAQs

What is Recursion?

Recursion in programming is a method where the solution to a problem depends on solutions to smaller instances of the same problem. Essentially, a recursive function is a function that calls itself during its execution. This enables the function to be repeated several times, as it can call itself during its execution.

What is Iteration?

Iteration in programming is a process wherein a set of instructions or structures are repeatedly executed until some condition is met. We often use loops for iteration in Python, such as for and while loops.

What are the key differences and similarities between recursion and iteration?

Recursion is a technique in which the function calls itself in its body to solve the problem, typically breaking into smaller and more manageable sub-problems. In contrast, Iteration is a technique that repetitively executes a code block until the condition is unmet. Recursion follows the divide and conquers approach, while Iteration follows the sequential execution approach to solve the problem. The time complexity of recursion is higher than Iteration due to the overhead of maintaining the function call stack. Iteration is faster than recursion due to less memory usage. Iteration is preferred for loops, while recursion is used for functions.

About the Author