3 Recursion
3 Recursion
(COMP-112)
Message(5);
Value of times: 3
Value of times: 2
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,
14-9
Recursive Function
#include <iostream>
void message(int);
int main() {
message(5);
return 0;
//************************************************************
message called with 5 in times.
// Definition of function message. If the value in times is *
// greater than 0, the message is displayed and the function * This is a recursive function.
// is recursively called with the argument times - 1. *
message called with 4 in times.
//************************************************************
{ cout << "message called with " << times message called with 3 in times.
<< " in times.\n";
This is a recursive function.
if (times > 0)
}
message called with 1 in times.
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)
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!
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[]
{
#include <iostream>
using namespace std; if (str[subscript] == '\0')
// Function prototype {
int numChars(char, char [], int);
// Base case: The end of the st
int main() return 0;
{
char array[] = "abcddddef"; }
} 14-17
Printing a Sequence of
Numbers in Reverse
void print(int n) {
if ( n <= 0 )
return; //Base 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
Finding gcd
14-20
The Recursive gcd
Function
14-21
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-22
Recursion
5th Fib. Number fib 5
fib 4 + fib 3
fib 1 + fib 0
=5
Recursive Fibonacci
Function
0;
14-24
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
14-25