1 Dr. Chow-Sing LinRecursion - CH 10 Problem Solving and Program Design in C Chapter 9 Recursion Chow-Sing Lin
Recursive A function that calls itself is said to be recursive. Use recursion as an alternative to iteration (looping). A recursive solution is less efficient than an iterative solution in terms of computation time due to the overhead for the extra function calls. The use of recursion enables us to specify a very natural, simple solution to a problem that would otherwise be very difficult to solve. 2 Dr. Chow-Sing LinRecursion - CH 10
3 Dr. Chow-Sing LinRecursion - CH 10 The Nature of Recursion One or more simple cases of the problem have a straightforward, non-recursive solution The other cases can be redefined in terms of problems that are closer to the simple cases By applying this redefinition process every time the recursive function is called, eventually the problem is reduced entirely to simple cases, which are relatively easy to solve
4 Dr. Chow-Sing LinRecursion - CH 10 Recursive Algorithm The recursive algorithms that we write will generally consist of an if statement –If this is a simple case solve it else redefine the problem using recursive
5 Dr. Chow-Sing LinRecursion - CH 10 Splitting a Problem into Smaller Problems Problem of size n –We can spilt the problem into a problem of size 1 (a simple case which we can solve) and size n-1. –And spilt problem n-1 into size 1 、 size n-2 –…… If we split the problem n-1 times, we will end up with n problems of size 1, all of which we can solve.
6 Dr. Chow-Sing LinRecursion - CH 10 Example 9.1 The problem of multiplying 6 by 3 Can split two problems 1.Multiply 6 by 2 2.Add 6 to the result of problem Multiply 6 by 2 can spilt 1.Multiply 6 by Multiply 6 by Add 6 to the result of problem Add 6 to the result of problem
7 Dr. Chow-Sing LinRecursion - CH 10 Recursive Function multiply
8 Dr. Chow-Sing LinRecursion - CH 10 Example 9.2 Develop a function to count the number of times a particular character appears in a string –Count (‘s’, “Mississippi sassafras”) –Should return the value 8 Can be solved by using a loop!
9 Dr. Chow-Sing LinRecursion - CH 10 Redefined the problem Count s ’s in “ Mississippi sassafras ” –Count s ’s in “ M ” –Count s ’s in “ ississippi sassafras ”
10 Dr. Chow-Sing LinRecursion - CH 10 Recursive Function to Count a Character in a String
11 Dr. Chow-Sing LinRecursion - CH 10 Tracing a Recursive Function Multiply(6, 3) by drawing an activation frame corresponding to each call of the function Activation frame shows the parameter values for each call and summarizes the execution of the call
12 Dr. Chow-Sing LinRecursion - CH 10 Trace of Function multiply
13 Dr. Chow-Sing LinRecursion - CH 10 Example 9.3 Take n words of input and prints them in reverse order reverse_input_words(5) Input –the –course –of –human –events Output will be events human of course the
14 Dr. Chow-Sing LinRecursion - CH 10 Function reverse_input_words
15 Dr. Chow-Sing LinRecursion - CH 10 Trace of reverse_input_words(3) Input “bits” “and” “bytes“ Output “bytes“ “and” “bits”
16 Dr. Chow-Sing LinRecursion - CH 10 Trace of reverse_input_words(3) (cont.)
17 Dr. Chow-Sing LinRecursion - CH 10 Parameter and Local Variable Stacks C uses the stack (FILO)data structure to keep the track of recursive calls. How to keep track of n and word ? –When executing a call to reverse_input_word, push the parameter value associated with the call on the top of the parameter stack, and push a new undefined cell on the top of the stack maintained for the local variable word. –A return from reverse_input_word pops each stack, removing the top value.
18 Dr. Chow-Sing LinRecursion - CH 10 Parameter and Local Variable Stacks (cont.) 3 bits nword Word “bits” is stored in word just before the second call to resverse_input_words 2 3 nword and bits second call to reverse_input_words and “bits” is stored in word bytes and bits nword third call to reverse_input_words and “bytes” is stored in word
19 Dr. Chow-Sing LinRecursion - CH 10 Parameter and Local Variable Stacks (cont.) 3 bits nword 2 3 nword and bits bytes and bits nword Output “bytes” After first return Output “and” After second return Output “bits”
20 Dr. Chow-Sing LinRecursion - CH 10 Trace Recursive Function Trace multiply(8, 3) by inserting debugging print statements show entry and exit from the function.
21 Dr. Chow-Sing LinRecursion - CH 10 Trace Recursive Function (cont.) Output trace from multiply(8, 3)
Recursive Mathematical Function Many mathematical functions can be defined recursively. N! –0! is 1 –N! is Nx(N-1)!, for N > 0 22 Dr. Chow-Sing LinRecursion - CH 10
23 Dr. Chow-Sing LinRecursion - CH 10 Example 9.4 n!
24 Dr. Chow-Sing LinRecursion - CH 10 Trace of fact = factorial(3)
25 Dr. Chow-Sing LinRecursion - CH 10 Iterative Function factorial
26 Dr. Chow-Sing LinRecursion - CH 10 Example 9.5 Fibonacci number
27 Dr. Chow-Sing LinRecursion - CH 10 Example 9.6 Greatest common divisor –gcd(m,n) Ex: gcd(6,21)=3 Spilt –gcd(m,n) is n if n divides m evenly –gcd(m,n) is gcd(n,remainder of m divided by n) otherwise
28 Dr. Chow-Sing LinRecursion - CH 10 Program Using Recursive Function gcd
29 Dr. Chow-Sing LinRecursion - CH 10 Program Using Recursive Function gcd (cont.)
30 Dr. Chow-Sing LinRecursion - CH 10 Recursive Function with Array and String Parameter Finding Capital Letters in a String –Finding capital letters in” WhosYourDaddy ” WYD Output is “ WYD ”
31 Dr. Chow-Sing LinRecursion - CH 10 Recursive Function with Array and String Parameter (cont.) Data Requirements –Problem Input char *str /* a string from which to extract capital letters */ –Problem Output char *caps /* the capital letters from str */
32 Dr. Chow-Sing LinRecursion - CH 10 Recursive Function with Array and String Parameter (cont.) Algorithm 1. if str is the empty string 2. Store empty string in caps ( a string with no letters certainly has no caps) else 3. if initial letters of str is a capital letter 4. Store in caps this letter and the capital letters from the rest of str else 5. Store in caps the capital letters from the rest of str
33 Dr. Chow-Sing LinRecursion - CH 10 Recursive Function with Array and String Parameter (cont.)
34 Dr. Chow-Sing LinRecursion - CH 10 Trace of Call to Recursive Function find_caps Printf(“Capital letters in JoJo are %s\n”,find_caps(caps,“JoJo”));
35 Dr. Chow-Sing LinRecursion - CH 10 Sequence of Events for Trace find_caps
36 Dr. Chow-Sing LinRecursion - CH 10 Recursive Selection Sort Selection Sort that fills the array from the bottom up
37 Dr. Chow-Sing LinRecursion - CH if n is 1 2. the array is sorted else 3.Place the largest array value in last array element 4.Sort the subarray which excludes the last array element (array[0]….array[n-2]) Recursive Algorithm for Selection Sort
38 Dr. Chow-Sing LinRecursion - CH 10 Recursive Selection Sort
39 Dr. Chow-Sing LinRecursion - CH 10 Operations on Sets Develop set operations, , , , Also, develop to check that a certain set is valid, to check for the empty set, and to print a set in standard set notation Analysis –Strings can be of varying sizes and can be empty –If characters array that is to hold a set is declared to have one more than the number of characters in the universal set (allow room for the null character) –Then set operations should never produce a string that will overflow the array
40 Dr. Chow-Sing LinRecursion - CH 10 Design Algorithm –Is_empty(set) 1. Is initial character ‘\0’? –Is_element(ele,set) 1. if is_empty(set) /* simple case1 */ 2. Answer is false else if initial character of set matches ele /* simple case1 */ 3. Answer is ture else 4. Answer depends on whether ele /* recursive step */ is in the rest of set
41 Dr. Chow-Sing LinRecursion - CH 10 Design (cont.) Algorithm Is_set(set) 1. if is_empty(set) /* simple case1 */ 2. Answer is true else if is_element(initial set character, rest of set) /* simple case2 */ 3. Answer is false else 4. Answer depends on whether rest of set is a valid set /* recursive step */
42 Dr. Chow-Sing LinRecursion - CH 10 Design (cont.) Algorithm is_subset(sub, set) 1. if is_empty(sub) /* simple case 1 */ 2. Answer is true else if initial character of sub is not an element of set 3. Answer is false /* simple case 2 */ else 4. Answer depends on whether rest of sub is a subset of set /* recursive steps */
43 Dr. Chow-Sing LinRecursion - CH 10 Design (cont.) Algorithm Union of set1 and set2 1. if is empty(set1) /* simple case */ 2. Result is set2 /* recursive steps */ else if initial character of set1 is also an element of set2 3. Result is the union of the rest of set1 with set2 else /* case 1 */ 4. Result includes initial character of set1 and the union of the rest of set1 with set2 /* case 2 */
44 Dr. Chow-Sing LinRecursion - CH 10 Design (cont.) Algorithm Print_set(set) 1.Output a { 2. if set is not empty, print elements separated by commas 3.Output 1}
45 Dr. Chow-Sing LinRecursion - CH 10 Design (cont.) Algorithm print_with_commas(set) 1. if set has exactly one element 2.Print it else 3. Print initial element and comma 4.print_with_commas the rest of set
46 Dr. Chow-Sing LinRecursion - CH 10 Recursive Set Operations on Sets Represented as Character Strings
47 Dr. Chow-Sing LinRecursion - CH 10
48 Dr. Chow-Sing LinRecursion - CH 10
49 Dr. Chow-Sing LinRecursion - CH 10
50 Dr. Chow-Sing LinRecursion - CH 10
51 Dr. Chow-Sing LinRecursion - CH 10
52 Dr. Chow-Sing LinRecursion - CH 10 Towers of Hanoi Move n disks from peg A to peg C using peg B as needed –Only one disk at a time may be moved and this disk must be the top disk on a peg –A larger disk can never be placed on top of a smaller disk
53 Dr. Chow-Sing LinRecursion - CH 10 Towers of Hanoi Analysis 1.Move four disks from peg A to peg B 2.Move disk 5 from peg A to peg C 3.Move four disks from peg B to peg C
54 Dr. Chow-Sing LinRecursion - CH 10 Towers of Hanoi Analysis (cont.) 3.1 Move three disks from peg B to peg A 3.2 Move disk 4 from peg B to peg C 3.3 Move three disks from peg A to peg C Step 3.3 can spilt …..
55 Dr. Chow-Sing LinRecursion - CH 10 Towers of Hanoi Data Requirements Problem Inputs –int n /* the number of disk to be moved */ –char form_peg /* the from peg */ –char to_peg /* the to peg */ –char aux_peg /*the auxiliary peg */ Problem Output A list of individual disk moves
56 Dr. Chow-Sing LinRecursion - CH 10 Towers of Hanoi Design Algorithm 1. if n is 1 then 2. Move disk 1from the from peg to the to peg else 3. Move n-1 disks from the from peg to the auxiliary peg using the to peg 4. Move disk n from the from peg to the to peg 5. Move n-1 disks from the auxiliary peg to the to peg using the from peg
57 Dr. Chow-Sing LinRecursion - CH 10 Recursive Function tower
58 Dr. Chow-Sing LinRecursion - CH 10 Trace of tower ('A', 'C', 'B', 3)
59 Dr. Chow-Sing LinRecursion - CH 10 Output Generated by tower('A', 'C', 'B', 3)
60 Dr. Chow-Sing LinRecursion - CH 10 Common Program Error Most common problem with a recursive function is that it may not terminate properly –Make sure that you identify all simple case and provide a terminating condition for each one –Be sure that each recursive step redefines the problem in terms of arguments that are closer to simple case so that repeated recursive calls will eventually lead to simple cases only
61 Dr. Chow-Sing LinRecursion - CH A B C