0% found this document useful (0 votes)
13 views38 pages

Recursion and Iteration

Uploaded by

golug971847
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views38 pages

Recursion and Iteration

Uploaded by

golug971847
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Recursion &

Iteration
What is Recursion?
The process in which a function calls itself directly or indirectly is called
recursion and the corresponding function is called a recursive function.
Using a recursive algorithm, certain problems can be solved quite easily.
Examples of such problems are Towers of Hanoi (TOH),
Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. A
recursive function solves a particular problem by calling a copy of itself
and solving smaller subproblems of the original problems. Many more
recursive calls can be generated as and when required. It is essential to
know that we should provide a certain case in order to terminate this
recursion process. So we can say that every time the function calls itself
with a simpler version of the original problem.
Recursion is mainly of two types depending on whether a function calls
itself from within itself or more than one function call one another
mutually. The first one is called direct recursion and another one is
called indirect recursion. Thus, the two types of recursion are:

1. Direct Recursion: These can be further categorized into four types:


Tail Recursion: If a recursive function calling itself and that recursive call
is the last statement in the function then it’s known as Tail Recursion.
After that call the recursive function performs nothing. The function
has to process or perform any operation at the time of calling and it
does nothing at returning time.
Head Recursion: If a recursive function calling itself and that recursive
call is the first statement in the function then it’s known as Head
Recursion. There’s no statement, no operation before the call. The
function doesn’t have to process or perform any operation at the time
of calling and all operations are done at returning time.
Tree Recursion: To understand Tree Recursion let’s first understand
Linear Recursion. If a recursive function calling itself for one time then
it’s known as Linear Recursion. Otherwise if a recursive function calling
itself for more than one time then it’s known as Tree Recursion.
Nested Recursion: In this recursion, a recursive function will pass the
parameter as a recursive call. That means “recursion inside recursion”.
2. Indirect Recursion: In this recursion, there may be more than one
functions and they are calling one another in a circular manner.

From the above diagram fun(A) is calling for fun(B), fun(B) is calling for
fun(C) and fun(C) is calling for fun(A) and thus it makes a cycle.
Need of Recursion

Recursion is an amazing technique with the help of which we can


reduce the length of our code and make it easier to read and write.
It has certain advantages over the iteration technique. A task that
can be defined with its similar subtask, recursion is one of the best
solutions for it. For example, the factorial of a number.
Properties of Recursion:

Performing the same operations multiple times with different inputs.


In every step, we try smaller inputs to make the problem smaller.
Base condition is needed to stop the recursion otherwise, an infinite
loop will occur.
Algorithm: Steps
The algorithmic steps for implementing recursion in a function are as follows:

Step 1 - Define a base case: Identify the simplest case for which the solution is known or trivial.
This is the stopping condition for the recursion, as it prevents the function from infinitely calling
itself.

Step 2 - Define a recursive case: Define the problem in terms of smaller subproblems. Break the
problem down into smaller versions of itself, and call the function recursively to solve each
subproblem.

Step 3 - Ensure the recursion terminates: Make sure that the recursive function eventually
reaches the base case, and does not enter an infinite loop.

Step 4 - Combine the solutions: Combine the solutions of the subproblems to solve the original
problem.
What is Iteration?
When there is a repetition or loop, it is known as iterative. In Iteration,
we prefer loops to perform the group of instructions repetitively until
the state of the iteration becomes wrong.

A program is called recursive when an entity calls itself. A program is


called iterative when there is a loop (or repetition).
Difference between Recursion and Iteration
Implement binary search program in C using iterative and recursive approach
What is Binary Search?
Binary Search is an interval searching algorithm that searches for an item in the
sorted list. It works by repeatedly dividing the list into two equal parts and then
searching for the item in the part where it can possibly exist.

Rules to Apply Binary Search


Unlike linear search, there are a few conditions for applying binary search:

The list must be sorted.


Random access to the list members.
It means that we cannot use the binary search with unsorted or linked data
structures.
Algorithm for Binary Search in C
Let key be the element we are searching for, and the array be sorted in the ascending order.
1. Compare key with the middle element of the array.
2. If key matches with the middle element, we return the index of the middle element.
3. Else if key is greater than the middle element, it means that key can only lie in the right
half subarray after the middle element. So we repeat steps 1 to 4 for the right half subarray
and leave the left half subarray.
4. Else if key is smaller than the middle element, it means that target can only lie in the left
half subarray before the middle element. So, we repeat steps 1 to 4 for the left half
subarray.
5. We will keep doing that till we find key or there is no element left in the subarray being
considered.
As we can see, the binary search ignores the half elements of the subarray after each pass.
Due to this, it is able to reduce the time required for searching the element in the array as
compared to linear search.
Working of Binary Search in C
Lets understand the working of above algorithm using an example. Consider an
array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91} and the key = 23
Problem Solving using Iteration and Recursion
Implementation of the Binary Search in C
In C, binary search can be implemented using two approaches:

1. Iterative Implementation
2. Recursive Implementation
1. Iterative Implementation of Binary Search in C
Create a function that takes an array, left index, right index, and the key to be
searched.
Use a loop to iterate while the subarray has elements i.e. left < right.
Calculate the midpoint mid.
Compare the key with the middle element i.e. arr[mid]
If the key matches the middle element, return mid.
If the key is greater, adjust the left index to search the right subarray by
making left = mid + 1.
If the key is smaller, adjust the right index to search the left subarray by
making right = mid – 1.
If the key is not found, return -1.
// C Program to implement binary search using iteration
#include <stdio.h>

int binarySearch(int arr[], int left, int right, int key) {

// Loop will run till left > right. It means that there
// are no elements to consider in the given subarray
while (left <= right) {

// calculating mid point


int mid = left + (right - left) / 2;

// Check if key is present at mid


if (arr[mid] == key) {
return mid;
}
/ If key greater than arr[mid], ignore left half
if (arr[mid] < key) {
left = mid + 1;
}

// If key is smaller than or equal to arr[mid],


// ignore right half
else {
right = mid - 1;
}
}

// If we reach here, then element was not present


return -1;
}
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int size = sizeof(arr) / sizeof(arr[0]);

// Element to be searched
int key = 23;

int result = binarySearch(arr, 0, size - 1, key);


if (result == -1) {
printf("Element is not present in array");
}
else {
printf("Element is present at index %d", result);
}
return 0;
}
Time Complexity: O(log N), where N is the number of elements in the array.

Auxiliary Space: O(1)


2. Recursive Implementation of Binary Search in C
Create a function that takes an array, left index, right index, and the key to
be searched.
Check if the subarray has elements to search i.e. left < right. If not, return -1.
Calculate the midpoint mid.
Compare the key with arr[mid].
If the key matches the middle element, return mid.
If the key is smaller, call the function again for the left subarray by passing
right = mid – 1.
If the key is larger, call the function again for the right subarray by passing
left = mid + 1.
The following C program implements the binary search algorithm using recursion:
#include <stdio.h>

int binarySearch(int arr[], int left, int right, int key) {

// checking if there are elements in the subarray


if (right >= left) {

// calculating mid point


int mid = left + (right - left) / 2;

// If the key is present at the middle itself


if (arr[mid] == key)
return mid;
/ If key is smaller than arr[mid], then it can only
// be present in left subarray
if (arr[mid] > key) {
return binarySearch(arr, left, mid - 1, key);
}

// Else the key can only be present in right


// subarray
return binarySearch(arr, mid + 1, right, key);
}

// We reach here when element is not present in array


return -1;
}
int main(void) {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int size = sizeof(arr) / sizeof(arr[0]);

// element to be searched
int key = 23;

int index = binarySearch(arr, 0, size - 1, key);


if (index == -1) {
printf("Element is not present in array");
}
else {
printf("Element is present at index %d", index);
}
Time Complexity: O(log N)
Auxiliary Space: O(log N), where N is the number of elements in the
array.
C Program To Print Fibonacci Series Using Iterative Method
#include <stdio.h>

void printFibonacci(int n){


int n1 = 0, n2 = 1, n3;
printf("%d %d ", n1, n2); // printing 0 and 1

for(int i=2; i<n; i++){


n3 = n1 + n2;
printf("%d ", n3);
n1 = n2;
n2 = n3;
}
}
int main(){
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
printFibonacci(n);
return 0;
}
C Program To Print Fibonacci Series Using Recursion Method
#include <stdio.h>
void printFibonacci(int n){
static int n1 = 0, n2 = 1, n3;
if(n > 0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ", n3);
printFibonacci(n-1);
}
}
int main(){
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
printf("%d %d ", 0, 1); // printing 0 and 1
printFibonacci(n-2); // n-2 because 2 numbers are already printed
return 0;
}
Tower of Hanoi problem
Tower of Hanoi is a mathematical puzzle where we have three rods and
n disks. The objective of the puzzle is to move the entire stack to
another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks
and placing it on top of another stack i.e. a disk can only be moved
if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
C Program for Tower of Hanoi
#include <stdio.h>

// C recursive function to solve tower of hanoi puzzle


void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}
Output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Time Complexity: O(2n)
Auxiliary Space: O(n)

You might also like