Recursion: National University of Computer & Emerging Sciences
Recursion: National University of Computer & Emerging Sciences
(CS 217)
Message(5);
Value of times: 3
Value of times: 2
• Indirect recursion
– function A calls function B, and function B calls
function A. Or,
14-9
Recursive Function
#include <iostream>
using namespace std;
void message(int);
int main() {
message(5);
return 0;
}
//************************************************************
// Definition of function message. If the value in times is *
// greater than 0, the message is displayed and the function message
* called with 5 in times.
// is recursively called with the argument times - 1. This
* is a recursive function.
message
//************************************************************ called with 4 in times.
void message(int times) This is a recursive function.
{ cout << "message called with " << times message called with 3 in times.
This is a recursive function.
<< " in times.\n"; message called with 2 in times.
if (times > 0) This is a recursive function.
{ message called with 1 in times.
cout << "This is a recursive function.\n"; This is a recursive function.
message(times - 1); message called with 0 in times.
} message returning with 0 in times.
message returning with 1 in times.
message returning with 2 in times.
cout << "message returning with " << times; message returning with 3 in times.
cout << " in times.\n"; message returning with 4 in times.
return; message returning with 5 in times.
} Recursion
Recursion
To build all recursive functions:
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;
//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!
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
int numChars(char search, char str[], int subscript)
#include
{ <iostream>
using ifnamespace std;
(str[subscript] == '\0')
{
// Function prototype
// Base case: The end of the string is reached.
int numChars(char, char [], int);
return 0;
}
int main()
else if (str[subscript] == search)
{
{
char array[] = "abcddddef";
/* Recursive case: A matching character was found.
Return 1 plus the number of times the search character
/* appears
Display in
the the
number
restofoftimes the letter
the string.*/
'd' appears in the string. */
return 1 + numChars(search, str,subscript+1);
}
cout << "The letter d appears "
else
<< numChars('d', array, 0) << " times.\n";
{
return /* 0;
Recursive case: A character that does not match the
search character was found. Return the number of times
} the search character appears in the rest of the string.
*/
return 0+ numChars(search, str, subscript+1); 14-17
}
}
Finding gcd
14-18
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-19
Solving Recursively Defined Problems
• The natural definition of some problems leads to
a recursive solution
• Recursive solution:
fib(n) = fib(n – 1) + fib(n – 2);
• Base cases: n == 0, n == 1
14-20
Recursion
5th Fib. Number fib 5
fib 4 + fib 3
fib 1 + fib 0
=8
Recursive Fibonacci Function
14-22
Printing a Sequence of Numbers in Reverse
void print(int n) {
if ( n <= 0 )
return; //Terminating condition
print(3) produces 3 2 1
Printing a Sequence of Numbers in
Ascending Order
Example:
Input Number: 5
Output: 1 2 3 4 5
Recursive Algorithms… Examples
– The Towers of Hanoi
– Binary Search Algorithm
– Height of a Binary Tree
–…
14-26
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
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
14-34
Recursion
37
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