Download presentation
Presentation is loading. Please wait.
Published byAnnabel Allison Modified over 9 years ago
1
Programming Principles II Lecture Notes 5 Recursion Andreas Savva
2
2 A function that calls itself. A function that calls itself. Every recursive process consists of two parts: Every recursive process consists of two parts: A base case that is processed without recursion. A base case that is processed without recursion. A general method that reduces a particular case to one or more of the smaller cases, making progress towards eventually reducing the problem all the way to the base case. A general method that reduces a particular case to one or more of the smaller cases, making progress towards eventually reducing the problem all the way to the base case. Recursion
3
3Memory Recursive Procedure void Display() { int n; cin >> n; if (n != -999) { Display(); cout << n << ’ ’; } void main() { Display(); } main 1 3 12 8 -999 Display n1 n3 n12 n8 n-999 81231
4
4Memory Recursive Procedure #include using namespace std; void display(int n, char c) { if (n != 0) { cout << c; display(n-1,c+1); } void main() { display(4,’A’); } mainABCD displayn4c’A’ n3c’B’ n2c’C’ n1c’D’ n0c’E’
5
5 Exercise #include 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’); } 7123456789123456
6
6 Mathematical Recursion Base case: f(0) = 0 Base case: f(0) = 0 Recursion: f(n) = n + f(n-1) for n > 0 Recursion: f(n) = n + f(n-1) for n > 0 f(5)= 5 + f(4) = 5 + 4 + f(3) = 5 + 4 + 3 + f(2) = 5 + 4 + 3 + 2 + f(1) = 5 + 4 + 3 + 2 + 1 + f(0) = 5 + 4 + 3 + 2 + 1 + 0 = 15
7
7 Factorial – A Recursive Definition 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); }
8
8MemoryFactorial(4) int factorial(int n) { if (n == 0) return 1; else return n * facorial(n-1); } void main() { cout << factorial(4); }main() 24 f(4)n4 f(3)n3 f(2)n2 f(1)n1 f(0)n0 = 4 * f(3) = 3 * f(2) = 2 * f(1) = 1* f(0) = 1 1 = 1 * 1 = 1 = 2 * 1 = 2 2 = 3 * 2 = 6 6 = 4 * 6 = 24 24
9
9 When not to use Recursion Consider the following two functions for calculating factorial: Recursive: int factorial(int n) { if (n == 0) return 1; return n * factorial(n − 1); }Non-recursive: int factorial(int n) { int count, product = 1; for (count = 1; count <= n; count++) product *= count; return product; }
10
10 factorial(5) - Recursive 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
11
11 Question Which of the two functions uses less storage space? Which of the two functions uses less storage space? The recursive one has one variable The recursive one has one variable The iterative one has three variables The iterative one has three variables But actually the recursive program will set up a stack and fill it in with n+1 numbers: But actually the recursive program will set up a stack and fill it in with n+1 numbers: n, n-1, n-2, …, 2, 1, 0 Thus, the recursive function keeps more storage, and it will take more time as well, since it must store and retrieve all the numbers as well as multiply them. Thus, the recursive function keeps more storage, and it will take more time as well, since it must store and retrieve all the numbers as well as multiply them.
12
12 Function Power – n r Base case: 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); }
13
13Memory Function Power #include 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() 16 f(2,4)n2r4 f(2,3)n2r3 f(2,2)n2r2 f(2,1)n2r1 f(2,0)n2r0 = 2 * f(2,3) = 2 * f(2,2) = 2 * f(2,1) = 2 * f(2,0) = 1 1 = 2 * 1 = 2 2 = 2 * 2 = 4 4 = 2 * 4 = 8 8 = 2 * 8 = 16 16
14
14 Fibonacci recursive function Definition: Fibonacci numbers are denoted by the recurrence relation Fibonacci numbers are denoted by the recurrence relation F 0 = 0, F 1 = 1, F n = F n−1 + F n−2 for n ≥ 2 int fibonacci(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fibonacci(n-1) + fibonacci(n-2); } 0 th 1 st 2 nd 3 rd 4 th 5 th 6 th 7 th 8 th … 01123581321… term
15
15 fibonacci(7)
16
16 Fibonacci iterative function int fibonacci(int n) { }
17
17 Recursion Vs Iteration RecursionIteration Readability Duplicate tasks
18
18 Designing Recursive Algorithms Find the key step. Begin by asking yourself, “How can this problem be divided into parts?” Find the key step. Begin by asking yourself, “How can this problem be divided into parts?” Find a stopping rule. This stopping rule is usually the small, special case that is trivial or easy to handle without recursion. Find a stopping rule. This stopping rule is usually the small, special case that is trivial or easy to handle without recursion. Combine the stopping rule and the key step, using an if- statement to select between them. Combine the stopping rule and the key step, using an if- statement to select between them. Check termination. Verify that the recursion will always terminate. Be sure that your algorithm correctly handles extreme cases. Check termination. Verify that the recursion will always terminate. Be sure that your algorithm correctly handles extreme cases.
19
19 Exercise 1 What is the output of the following program? What is the output of the following program? #include using namespace std; void display(int n) { if (n != 0) { cout << n; display(n-1); cout << n; } void main() { display(5); }
20
20 Exercise 2 Write a recursive function “Sum” that will take an integer number n and it will return the summation of all the numbers between 1 and n. If n ≤ 0 the function should return zero. Write a recursive function “Sum” that will take an integer number n and it will return the summation of all the numbers between 1 and n. If n ≤ 0 the function should return zero. Examples: Sum(4) = 1 + 2 + 3 + 4 = 10 Sum(4) = 1 + 2 + 3 + 4 = 10 Sum(0) = 0 Sum(0) = 0 Sum(-4) = 0 Sum(-4) = 0 Write the same function without recursion. Write the same function without recursion.
21
21 Exercise 3 Write a recursive function “Summation” that will take two integer numbers n and m and it will return the summation of all the numbers between n and m. If n > m the function should return zero. Write a recursive function “Summation” that will take two integer numbers n and m and it will return the summation of all the numbers between n and m. If n > m the function should return zero. Examples: Summation(3, 7) = 3 + 4 + 5 + 6 + 7 = 25 Summation(3, 7) = 3 + 4 + 5 + 6 + 7 = 25 Summation(7, 2) = 0 Summation(7, 2) = 0 Summation(4,4) = 4 Summation(4,4) = 4 Summation(-3,1) = -5 Summation(-3,1) = -5 Write the same function without recursion. Write the same function without recursion.
22
22 Exercise 4 Write a recursive procedure “Display” that will take an integer number n and display all the numbers between 1 and n in reverse order. If n ≤ 0 it should not display anything. Write a recursive procedure “Display” that will take an integer number n and display all the numbers between 1 and n in reverse order. If n ≤ 0 it should not display anything. Examples: Display(5);will display: 5 4 3 2 1 Display(5);will display: 5 4 3 2 1 Display(3);will display: 3 2 1 Display(3);will display: 3 2 1 Write the same function without recursion. Write the same function without recursion.
23
23 Exercise 5 Write a recursive function “Multiply” that will take two integer numbers n and m and it will return the multiplication of all the numbers between n and m. If n > m the function should return zero. Write a recursive function “Multiply” that will take two integer numbers n and m and it will return the multiplication of all the numbers between n and m. If n > m the function should return zero. Examples: Multiply(2, 5) = 2 × 3 × 4 × 5 = 120 Multiply(2, 5) = 2 × 3 × 4 × 5 = 120 Multiply(7, 2) = 0 Multiply(7, 2) = 0 Multiply(4, 4) = 4 Multiply(4, 4) = 4 Multiply(-3, 1) = 0 Multiply(-3, 1) = 0 Write the same function without recursion. Write the same function without recursion.
24
24 Exercise 6 Write a recursive function “SumEven” that will take two integer numbers n and m and it will return the summation of all the even numbers between n and m. If n > m the function should return zero. Write a recursive function “SumEven” that will take two integer numbers n and m and it will return the summation of all the even numbers between n and m. If n > m the function should return zero. Examples: SumEven(3, 10) = 4 + 6 + 8 + 10 = 28 SumEven(3, 10) = 4 + 6 + 8 + 10 = 28 SumEven(7, 2) = 0 SumEven(7, 2) = 0 SumEven(4,4) = 4 SumEven(4,4) = 4 SumEven(3,3) = 0 SumEven(3,3) = 0 Write the same function without recursion. Write the same function without recursion.
25
25 Exercise 7 The greatest common divisor (gcd) of two positive integers is the largest integer that divides both of them. i.e. The greatest common divisor (gcd) of two positive integers is the largest integer that divides both of them. i.e. gcd(8,12) = 4 gcd(9,18) = 9 gcd(16,25) = 1 a) Write a non-recursive function, gcd(x,y) that searches through the positive integers until it finds the largest integer dividing both x and y. b) Write a recursive function, gcd(x,y) that implements Euclid’s algorithm: 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. c) Rewrite the function of part (b) into iterative form.
26
26 Exercise 8 The binomial coefficients can be defined by the following recurrence relation, which is the idea of Pascal’s triangle. The binomial coefficients can be defined by the following recurrence relation, which is the idea of Pascal’s triangle. C(n, 0) = 1 C(n, n) = 1 for n ≥ 0 C(n, k) = C(n-1, k) + C(n-1, k-1) for n > k > 0
27
27 Exercise 8 (continue) a) Write a recursive function to generate C(n, k) by the formula. b) Use the square array with n indicating the row and k the column, and write a non-recursive program to generate Pascal’s triangle in the lower left half of the array, that is, in the entries for which k ≤ n.
28
28 Exercise 9 What is the output of the following program? What is the output of the following program? #include using namespace std; void display(int n) { if (n > 0) { display(n-1); cout << n; display(n-1); } void main() { display(4); }
29
29 Exercise 10 What is the output of the following program? What is the output of the following program? #include using namespace std; void display(int n) { if (n > 0) { display(n-1); cout << n; } void main() { display(4); }
30
30 Exercise 11 What is the output of the following program? What is the output of the following program? #include using namespace std; void display(int n) { if (n > 0) { display(n-1); display(n-2); cout << n; } void main() { display(4); }
31
31 Exercise 12 What is the output of the following program? What is the output of the following program? #include 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); }
32
Exercise 13 An integer is printed with commas inserted every 3 positions from the right. That is, to print the number 12345678 as 12,345,678, the 678 cannot be printed until after the preceding part of the number is printed. Write a recursive function “PrintWithCommas” that will print its long integer parameter with commas inserted properly. An integer is printed with commas inserted every 3 positions from the right. That is, to print the number 12345678 as 12,345,678, the 678 cannot be printed until after the preceding part of the number is printed. Write a recursive function “PrintWithCommas” that will print its long integer parameter with commas inserted properly. You must be careful with leading zeros to ensure, for example, that the number 12,003 is printed properly. You must be careful with leading zeros to ensure, for example, that the number 12,003 is printed properly. 32
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.