Programming Programming Principles IIPrinciples II
Lecture Notes 5Lecture Notes 5RecursionRecursion
Andreas SavvaAndreas Savva
22
A function that calls itself.A function that calls itself.
Every recursive process consists of two Every recursive process consists of two parts:parts:
A base case that is processed without A base case that is processed without recursion.recursion.
A general method that reduces a particular A general method that reduces a particular case to one or more of the smaller cases, case to one or more of the smaller cases, making progress towards eventually reducing making progress towards eventually reducing the problem all the way to the base case.the problem all the way to the base case.
RecursionRecursion
33
MemoryMemory
Recursive Recursive ProcedureProcedure
void Display(){ int n; cin >> n; if (n != -999) { Display(); cout << n << ’ ’; }}
void main(){ Display();}
main
1 3 12 8 -999 <enter>
Displaynn11
Displaynn33
Displaynn1212
Displaynn88
Displaynn
-999-999
88 1212 33 11
44
MemoryMemory
Recursive Recursive ProcedureProcedure
#include <iostream>using namespace std;void display(int n, char c){ if (n != 0) { cout << c; display(n-1,c+1); }}
void main(){ display(4,’A’);}
mainAABBCCDD
displaynn44
cc’’A’A’
displaynn33
cc’’B’B’
displaynn22
cc’’C’C’
displaynn11
cc’’D’D’
displaynn00
cc’’E’E’
55
ExerciseExercise#include <iostream>using namespace std;void display(int n, int m, char c){ if (n==1 && m==1) cout << c; else if (n > 1) { cout << endl; display(n-1,m,c); } else if (m > 1) { cout << ’ ’; display(n,m-1,c); }}
void main(){ display(3,4,’7’);}
7
123456789 123456789
112233445566
66
Mathematical RecursionMathematical Recursion
Base case: Base case: f(0)f(0) = 0 = 0 Recursion: Recursion: f(n)f(n) = = n n ++ f(n-1) f(n-1) for for n n > 0> 0
f(5)f(5) = 5 + f(4)= 5 + f(4)= 5 + 4 + f(3)= 5 + 4 + f(3)= 5 + 4 + 3 + f(2)= 5 + 4 + 3 + f(2)= 5 + 4 + 3 + 2 + f(1)= 5 + 4 + 3 + 2 + f(1)= 5 + 4 + 3 + 2 + 1 + f(0)= 5 + 4 + 3 + 2 + 1 + f(0)= 5 + 4 + 3 + 2 + 1 + 0= 5 + 4 + 3 + 2 + 1 + 0= 15= 15
77
Factorial – A Recursive Factorial – A Recursive DefinitionDefinition
int factorial(int n)// Pre: n is a nonnegative integer// Post: Return the value of the factorial of n{ if (n == 0) return 1; else return n * factorial(n - 1);}
0 if )!1(
0 if 1!
nnn
nn
1 if 0( )
( 1) if 0
nf n
n f n n
88
MemoryMemoryFactorial(4)Factorial(4)
int factorial(int n){ if (n == 0) return 1; else return n * facorial(n-1);}
void main(){ cout << factorial(4);}
main()main()24
f(4)f(4)nn44
f(3)f(3)nn33
f(2)f(2)nn22
f(1)f(1)nn11
f(0)f(0)nn00
= 4 * f(3) = 4 * f(3)
= 3 * f(2) = 3 * f(2)
= 2 * f(1) = 2 * f(1)
= 1* f(0) = 1* f(0)
= 1= 1 11
= 1 * 1 = 1 = 1 * 1 = 1
= 2 * 1 = 2 = 2 * 1 = 2 22
= 3 * 2 = 6 = 3 * 2 = 6 66
= 4 * 6 = 24 = 4 * 6 = 24
2424
99
When not to use RecursionWhen not to use RecursionConsider the following two functions for calculating Consider the following two functions for calculating
factorial:factorial:
Recursive:Recursive:
int factorial(int n){if (n == 0) return 1;return n * factorial(n − 1);
}
Non-recursive:Non-recursive:
int factorial(int n){int count, product = 1;for (count = 1; count <= n; count++)
product *= count;return product;
}
1010
factorial(5) - Recursivefactorial(5) - Recursive
Example:Example:
factorial(5) = 5 * factorial(4)= 5 * (4 * factorial(3))= 5 * (4 * (3 * factorial(2)))= 5 * (4 * (3 * (2 * factorial(1))))= 5 * (4 * (3 * (2 * (1 *
factorial(0)))))= 5 * (4 * (3 * (2 * (1 * 1))))= 5 * (4 * (3 * (2 * 1)))= 5 * (4 * (3 * 6))= 5 * (4 * 6)= 5 * 24= 120
1111
QuestionQuestion
Which of the two functions uses less storage space?Which of the two functions uses less storage space? The recursive one has one variableThe recursive one has one variable The iterative one has three variablesThe iterative one has three variables
But actually the recursive program will set up a But actually the recursive program will set up a stack and fill it in with n+1 numbers:stack and fill it in with n+1 numbers:
n, n-1, n-2, … , 2, 1, 0n, n-1, n-2, … , 2, 1, 0
Thus, the recursive function keeps more storage, Thus, the recursive function keeps more storage, and it will take more time as well, since it must and it will take more time as well, since it must store and retrieve all the numbers as well as store and retrieve all the numbers as well as multiply them.multiply them.
1212
Function Power – Function Power – nn rr
0
1
1r r
n
n n n
1 if 0( , )
( , 1) if r 0
rf n r
n f n r
Base case:Base case:
Key step:Key step:
int power(int n, int r)// Pre: r is a nonnegative integer// Post: Return the value of n to the power r{ if (r == 0) return 1; else return n * power(n, r - 1);}
1313
MemoryMemory
Function PowerFunction Power
#include <iostream>using namespace std;int power(int n, int r){ if (r == 0) return 1; else return n * power(n,r-1);}
void main(){ cout << power(2,4);}
main()1616
f(2,4)nn22
rr44
f(2,3)nn22
rr33
f(2,2)nn22
rr22
f(2,1)nn22
rr11
f(2,0)nn22
rr00
= 2 * f(2,3) = 2 * f(2,3)
= 2 * f(2,2) = 2 * f(2,2)
= 2 * f(2,1) = 2 * f(2,1)
= 2 * f(2,0) = 2 * f(2,0)
= 1 = 1 11
= 2 * 1 = 2 = 2 * 1 = 2 22
= 2 * 2 = 4 = 2 * 2 = 4 44
= 2 * 4 = 8 = 2 * 4 = 8 88
= 2 * 8 = 16 = 2 * 8 = 16 1616
1414
Fibonacci recursive functionFibonacci recursive function
Definition:Definition: Fibonacci numbers Fibonacci numbers are denoted by the are denoted by the
recurrence relationrecurrence relationFF00 = 0 = 0, F, F11 = 1, = 1, F Fnn = = FFnn−1−1 + + FFnn−2−2 for for n n ≥ 2≥ 2
int fibonacci(int n){ if (n == 0) return 0; else if (n == 1) return 1; else return fibonacci(n-1) + fibonacci(n-2); }
00thth 11stst 22ndnd 33rdrd 44thth 55thth 66thth 77thth 88thth ……
00 11 11 22 33 55 88 1313 2121 ……
termterm
1515
fibonacci(7)fibonacci(7)
1616
Fibonacci iterative functionFibonacci iterative function
int fibonacci(int n){
}
1717
Recursion Vs IterationRecursion Vs Iteration
RecursionRecursion IterationIteration
ReadabilityReadability Duplicate tasksDuplicate tasks
1818
Designing Recursive Designing Recursive AlgorithmsAlgorithms
Find the key step. Begin by asking yourself, “How Find the key step. Begin by asking yourself, “How can this problem be divided into parts?”can this problem be divided into parts?”
Find a stopping rule. This stopping rule is usually Find a stopping rule. This stopping rule is usually the small, special case that is trivial or easy to the small, special case that is trivial or easy to handle without recursion.handle without recursion.
Combine the stopping rule and the key step, Combine the stopping rule and the key step, using an using an if-statement if-statement to select between them.to select between them.
Check termination. Verify that the recursion will Check termination. Verify that the recursion will always terminate. Be sure that your algorithm always terminate. Be sure that your algorithm correctly handles extreme cases.correctly handles extreme cases.
1919
Exercise 1Exercise 1 What is the output of the following program?What is the output of the following program?
#include <iostream>using namespace std;void display(int n){ if (n != 0) { cout << n; display(n-1); cout << n; }}void main(){ display(5);}
2020
Exercise 2Exercise 2
Write a recursive function “Sum” that will Write a recursive function “Sum” that will take an integer number take an integer number nn and it will return and it will return the summation of all the numbers between 1 the summation of all the numbers between 1 and and nn. If . If nn ≤≤ 0 the function should return 0 the function should return zero.zero.
ExamplesExamples:: Sum(4) = 1 + 2 + 3 + 4 = 10Sum(4) = 1 + 2 + 3 + 4 = 10 Sum(0) = 0Sum(0) = 0 Sum(-4) = 0Sum(-4) = 0
Write the same function without recursion.Write the same function without recursion.
2121
Exercise 3Exercise 3
Write a recursive function “Summation” that Write a recursive function “Summation” that will take two integer numbers will take two integer numbers nn and and mm and it and it will return the summation of all the numbers will return the summation of all the numbers between between nn and and mm. If . If nn > > mm the function the function should return zero.should return zero.
ExamplesExamples:: Summation(3, 7) = 3 + 4 + 5 + 6 + 7 = 25Summation(3, 7) = 3 + 4 + 5 + 6 + 7 = 25 Summation(7, 2) = 0Summation(7, 2) = 0 Summation(4,4) = 4Summation(4,4) = 4 Summation(-3,1) = -5Summation(-3,1) = -5
Write the same function without recursion.Write the same function without recursion.
2222
Exercise 4Exercise 4
Write a recursive procedure “Display” that Write a recursive procedure “Display” that will take an integer number will take an integer number nn and display and display all the numbers between 1 and all the numbers between 1 and nn in in reverse order. If reverse order. If nn ≤≤ 0 it should not 0 it should not display anything.display anything.
ExamplesExamples:: Display(5);Display(5); will display: will display: 5 4 3 2 15 4 3 2 1 Display(3);Display(3); will display:will display: 3 2 1 3 2 1
Write the same function without recursion.Write the same function without recursion.
2323
Exercise 5Exercise 5
Write a recursive function “Multiply” that will Write a recursive function “Multiply” that will take two integer numbers take two integer numbers nn and and mm and it will and it will return the multiplication of all the numbers return the multiplication of all the numbers between between nn and and mm. If . If nn > > mm the function the function should return zero.should return zero.
ExamplesExamples:: Multiply(2, 5) = 2 Multiply(2, 5) = 2 ×× 3 3 ×× 4 4 ×× 5 = 120 5 = 120 Multiply(7, 2) = 0Multiply(7, 2) = 0 Multiply(4, 4) = 4Multiply(4, 4) = 4 Multiply(-3, 1) = 0Multiply(-3, 1) = 0
Write the same function without recursion.Write the same function without recursion.
2424
Exercise 6Exercise 6
Write a recursive function “SumEven” that Write a recursive function “SumEven” that will take two integer numbers will take two integer numbers nn and and mm and it and it will return the summation of all the even will return the summation of all the even numbers between numbers between nn and and mm. If . If nn > > mm the the function should return zero.function should return zero.
ExamplesExamples:: SumEven(3, 10) = 4 + 6 + 8 + 10 = 28SumEven(3, 10) = 4 + 6 + 8 + 10 = 28 SumEven(7, 2) = 0SumEven(7, 2) = 0 SumEven(4,4) = 4SumEven(4,4) = 4 SumEven(3,3) = 0SumEven(3,3) = 0
Write the same function without recursion.Write the same function without recursion.
2525
Exercise 7Exercise 7
The The greatest common divisorgreatest common divisor (gcd) of two positive (gcd) of two positive integers is the largest integer that divides both of integers is the largest integer that divides both of them. i.e.them. i.e.
gcd(8,12) = 4gcd(8,12) = 4
gcd(9,18) = 9gcd(9,18) = 9
gcd(16,25) = 1gcd(16,25) = 1
a)a) Write a non-recursive function, gcd(x,y) that searches Write a non-recursive function, gcd(x,y) that searches through the positive integers until it finds the largest integer through the positive integers until it finds the largest integer dividing both x and y.dividing both x and y.
b)b) Write a recursive function, gcd(x,y) that implements Write a recursive function, gcd(x,y) that implements Euclid’s Euclid’s algorithm:algorithm: if y = 0, then the gcd of x and y is x; otherwise the if y = 0, then the gcd of x and y is x; otherwise the gcd of x and y is the same as the gcd of y and x % y.gcd of x and y is the same as the gcd of y and x % y.
c)c) Rewrite the function of part (b) into iterative form.Rewrite the function of part (b) into iterative form.
2626
Exercise 8Exercise 8 The The binomial coefficientsbinomial coefficients can be defined by the can be defined by the
following recurrence relation, which is the idea of following recurrence relation, which is the idea of Pascal’s triangle.Pascal’s triangle.
C(n, 0)C(n, 0) = 1 = 1
C(n, n)C(n, n) = 1 for = 1 for nn ≥ 0≥ 0
C(n, k)C(n, k) = = C(n-1, k)C(n-1, k) + + C(n-1, k-1)C(n-1, k-1) for for n n > > kk > 0 > 0
2727
Exercise 8 (continue)Exercise 8 (continue)
a)a)Write a recursive function to generate Write a recursive function to generate C(n, k)C(n, k) by the formula.by the formula.
b)b)Use the square array with Use the square array with nn indicating the row indicating the row and k the column, and write a non-recursive and k the column, and write a non-recursive program to generate Pascal’s triangle in the program to generate Pascal’s triangle in the lower left half of the array, that is, in the lower left half of the array, that is, in the entries for which entries for which kk ≤ ≤ nn..
2828
Exercise 9Exercise 9 What is the output of the following program?What is the output of the following program?
#include <iostream>using namespace std;void display(int n){ if (n > 0) { display(n-1); cout << n; display(n-1); }}void main(){ display(4);}
2929
Exercise 10Exercise 10
What is the output of the following program?What is the output of the following program?
#include <iostream>using namespace std;void display(int n){ if (n > 0) { display(n-1); display(n-1); cout << n; }}void main(){ display(4);}
3030
Exercise 11Exercise 11
What is the output of the following program?What is the output of the following program?
#include <iostream>using namespace std;void display(int n){ if (n > 0) { display(n-1); display(n-2); cout << n; }}void main(){ display(4);}
3131
Exercise 12Exercise 12 What is the output of the following program?What is the output of the following program?
#include <iostream>using namespace std;void display(int n){ if (n > 0) { display(n-1); display(n-2); cout << n; display(n-1); }}void main(){ display(4);}
Exercise 13Exercise 13 An integer is printed with commas inserted An integer is printed with commas inserted
every 3 positions from the right. That is, to every 3 positions from the right. That is, to print the number 12345678 as 12,345,678, the print the number 12345678 as 12,345,678, the 678 cannot be printed until 678 cannot be printed until afterafter the preceding the preceding part of the number is printed. Write a recursive part of the number is printed. Write a recursive function “PrintWithCommas” that will print its function “PrintWithCommas” that will print its longlong integer parameter with commas inserted integer parameter with commas inserted properly.properly.
You must be careful with leading zeros to You must be careful with leading zeros to ensure, for example, that the number 12,003 is ensure, for example, that the number 12,003 is printed properly.printed properly.
3232