0% found this document useful (0 votes)
10 views

1_Function_Recursion (1)

The document provides an introduction to recursion, explaining how recursive functions call themselves and the importance of base cases to prevent infinite loops. It includes examples of recursive functions for tasks such as summation, factorial calculation, and Fibonacci number generation, as well as the Towers of Hanoi problem. Additionally, it discusses the advantages and disadvantages of recursive versus iterative implementations.

Uploaded by

gajab3495
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

1_Function_Recursion (1)

The document provides an introduction to recursion, explaining how recursive functions call themselves and the importance of base cases to prevent infinite loops. It includes examples of recursive functions for tasks such as summation, factorial calculation, and Fibonacci number generation, as well as the Towers of Hanoi problem. Additionally, it discusses the advantages and disadvantages of recursive versus iterative implementations.

Uploaded by

gajab3495
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Recursion

Department of Computer Science & IT,


The University of Lahore
Introduction to Recursion
• A recursive function is one that calls itself.
void Message(void)
{
cout << "This is a recursive function.\n";
Message();
}

The above function displays the string


"This is a recursive function.\n", and then calls itself.

Can you see a problem with this function?


Recursion
• The function is like an infinite loop because there is
no code to stop it from repeating.

• Like a loop, a recursive function must have some


algorithm to control the number of times it repeats.
Recursion : Using Control Condition
void Message(int times)
{
if (times > 0)
{
cout << "This is a recursive function.\n";
Message(times ‑ 1);
}
return;
}

The function contains an if/else statement that controls the


repetition. For example, if we call the function:

Message(5);

The argument, 5, will cause the function to call itself 5 times.


Recursion : Using Control Condition
void Message(int times)
{
if (times > 0) // Base case
{
cout << "This is a recursive function.\n";
Message(times ‑ 1);
}
return;
}

• With each recursive call, the parameter controlling the


recursion should move closer to the base case

• Eventually, the parameter reaches the base case and the


chain of recursive calls terminates
void Message(int times)
{
if (times > 0)
1st call of the function {
cout << "This is a recursive function.\n";
Value of times: 5 Message(times ‑ 1);
}
2nd call of the function return;
Value of times: 4 }

3rd call of the function

Value of times: 3

4th call of the function

Value of times: 2

5th call of the function


This cycle repeats itself
until 0 is passed to the Value of times: 1
function.
6th call of the function

Depth of recursion: 6 Value of times: 0


Program Output
This is a recursive function.
This is a recursive function.
This is a recursive function.
This is a recursive function.
This is a recursive function.
What Happens When Called?
• Each time a recursive function is called, a new copy of
the function runs, with new instances of parameters
and local variables being created

• As each copy finishes executing, it returns to the copy of


the function that called it

• When the initial copy finishes executing, it returns to


the part of the program that made the initial call to the
function
14-8
Types of Recursion
• Direct recursion
– a function calls itself

• Indirect recursion
– function A calls function B, and function B calls
function A. Or,

– function A calls function B, which calls …, which calls


function A

14-9
Recursive Function
#include <iostream>
using namespace std;

void message(int);
int main() {
message(5);
return 0; message called with 5 in times.
}
This is a recursive function.

//************************************************************
message called with 4 in times.
// Definition of function message. If the value in times is *
This is a recursive function.
// greater than 0, the message is displayed and the function *
// is recursively called with the argument times - 1. *
message called with 3 in times.
//************************************************************
void message(int times) This is a recursive function.
{ cout << "message called with " << times
<< " in times.\n"; message called with 2 in times.
if (times > 0) This is a recursive function.
{
cout << "This is a recursive function.\n"; message called with 1 in times.
message(times - 1); This is a recursive function.
}
message called with 0 in times.
cout << "message returning with " << times; message returning with 0 in times.
cout << " in times.\n";
return; message returning with 1 in times.
} message returning with 2 in times.
Recursion
message returning with 3 in times.
Recursion
To build all recursive functions:

1. Define the base case(s)


2. Define the recursive case(s)
a) Divide the problem into smaller sub-
problems
b) Solve the sub-problems
c) Combine results to get answer

Sub-problems solved
as a recursive call to
the same function
Creating a Sum Function
• sum(10) = 10+9+…2+1 = 55
Creating a Sum function (Iterative)
//Our initial total is zero
int total = 0;

//We want the sum from 1 + 2 + ... + 9 + 10


int n = 10;

/* The following for loop will calculate the summation


from 1 – n */
for ( int i = 1; i <= n; i++ ) {
total = total + i;
}
Creating a Sum function (Recursive)
int sum(int n) {

//Return 0 when n is 0
if ( n <= 0 )
return 0;
else //recursive call
return n + sum(n-1);
}
The Recursive Factorial Function
• The factorial of a non-negative integer n is the product of
all positive integers less or equal to n

• Factorial of n is denoted by n!

• The factorial of 0 is= 1


0!=1
n ! = n x (n-1) x … x 2 x 1 if n > 0

14-15
The Recursive Factorial Function
• Factorial of n can be expressed in terms of the factorial of n-1
0!=1
n ! = n x (n-1) !
• The base case is n = 0

• Recursive function:

int factorial(int n)
{
if (n == 0)
return 1;
else
return n * factorial(n-1);
} 14-16
Character count - Recursive
#include <iostream>
using namespace std;

// Function prototype
int numChars(char, char [], int);

int main()
{
char array[] = "abcddddef";

/* Display the number of times the letter 'd' appears in the


string. */

cout << "The letter d appears "


<< numChars('d', array, 0) << " times.\n";

return 0;
}

14-17
int numChars(char search, char str[], int subscript)

if (str[subscript] == '\0')

// Base case: The end of the string is reached.

return 0;

else if (str[subscript] == search)

/* Recursive case: A matching character was found. Return 1


plus the number of times the search character appears in the rest of
the string.*/

return 1 + numChars(search, str,subscript+1);

}
Printing a Sequence of Numbers in Reverse

void print(int n) {

if ( n <= 0 )
return; //Base condition

cout << n << " "; //Prints number n


print(n-1); //Calls itself with (n-1)
return; //Returns from the function
}

print(3) produces  3 2 1
Printing a Sequence of Numbers in
Ascending Order

Example:
Input Number: 5
Output: 1 2 3 4 5
Finding gcd

14-21
The Recursive gcd Function
int gcd(int x, int y)
{
if (x % y == 0) //base case
return y;
else
return gcd(y, x % y);
}

14-22
Solving Recursively Defined Problems
• The natural definition of some problems leads to
a recursive solution

• Example: Fibonacci numbers:


1, 1, 2, 3, 5, 8, 13, 21, ...

• After the starting two numbers, each term is the


sum of the two preceding terms

• Recursive solution:
fib(n) = fib(n – 1) + fib(n – 2);

• Base cases: n == 0, n == 1 14-23


Recursion
5th Fib. Number fib 5

fib 4 + fib 3

fib 3 + fib 2 fib 2 + fib 1

fib 2 + fib 1 fib 1 + fib 0 fib 1 + fib 0

fib 1 + fib 0

=5
Recursive Fibonacci Function
#include <iostream>
using namespace std;
// Function to calculate Fibonacci number using recursion
int fibonacci(int n) {
if (n <= 1) // Base case: fib(0) = 0, fib(1) = 1
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
int main() {
int n;
cout << "Enter the number of terms for the Fibonacci series: ";
cin >> n;
cout << "Fibonacci series: ";
for (int i = 0; i < n; i++) {
cout << fibonacci(i) << " "; // Print Fibonacci numbers
}
cout << endl;
return 0;
} 14-25
Printing Patterns using Recursion

14-27
Printing Patterns using Recursion
Code credits: https://www.geeksforgeeks.org/

14-28
Printing Patterns using Recursion
Input:
Draw a Pyramid of size: 5

Output:
#
# #
# # #
# # # #
# # # # #

14-29
Printing Patterns using Recursion
Code credits: https://www.tutorialspoint.com/

14-30
The Towers of Hanoi
• Setup: 3 pegs, one has n disks on it, the other two pegs
empty. The disks are arranged in increasing diameter:
top bottom

• Objective: move the disks from peg 1 to peg 3:


– only one disk moves at a time
– all remain on pegs except the one being moved
– a larger disk cannot be placed on top of a smaller disk
at any time

14-31
The Towers of Hanoi
How it works:
n=1 Move disk from peg 1 to peg 3.
Done.

n=2 Move top disk from peg 1 to peg 2.


Move remaining disk from peg 1 to peg 3.
Move disk from peg 2 to peg 3.
Done.

14-32
Moving Three Discs
Outline of Recursive Algorithm

If n==0, do nothing (base case)


If n>0, then
a. Move the topmost n-1 disks from peg1 to peg2
b. Move the nth disk from peg1 to peg3
c. Move the n-1 disks from peg2 to peg3
end if

14-34
Recursion VS. Iteration
• Benefits (+), disadvantages(-) of Recursive
Implementation
+ Natural formulation of solution to certain problems
+ Results in shorter, simpler functions
– May not execute very efficiently

• Benefits (+), disadvantages(-) for iterative


Implementation
+ Executes more efficiently than recursion
– May not be as natural as recursion for some problems

14-38

You might also like