Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion (II) H&K Chapter 10 Instructor – Gokcen Cilingir Cpt S 121 (July 25, 2011) Washington State University.

Similar presentations


Presentation on theme: "Recursion (II) H&K Chapter 10 Instructor – Gokcen Cilingir Cpt S 121 (July 25, 2011) Washington State University."— Presentation transcript:

1 Recursion (II) H&K Chapter 10 Instructor – Gokcen Cilingir Cpt S 121 (July 25, 2011) Washington State University

2 Recall: recursive functions A function that calls itself is said to be recursive. Here are examples of “famous” recursively defined functions in math: factorial and fibonacci Base case/step Recursive case/step The ability to invoke itself enables a recursive function to be repeated with different parameter values

3 C. Hundhausen, A. O’Fallon3 Recall: recursion Problems that may be solved using recursion have these attributes: ◦ One or more simple cases have a straightforward, non- recursive solution ◦ The other cases may be defined in terms of problems that are closer to the simple cases ◦ Through a series of calls to the recursive function, the problem eventually is stated in terms of the simple cases image source: H&K, figure 10.1

4 Example 1 Write a function that performs multiplication through addition with the prototype: int multiply(int m, int n); Let’s recursively define multiply : base case: multiply (m,1) is m recursive case: multiply (m, n) is n + multiply (m, n-1)

5 Example 1 (cont’d) Here is the recursive C implementation of mult: int multiply (int m, int n) { int ans; if (n == 1) ans = m; // base case else ans = m + multiply (m, n – 1); // recursive case return ans; }

6 Tracing a recursive function image source: H&K, figure 10.5

7 Alternative tracing: execute the following code int multiply (int m, int n) { int ans; printf("Function called with m: %d, n: %d\n", m, n); if (n == 1) //base case { ans = m; } else // recursive case { ans = m + multiply (m, n - 1); } printf ("ans is: %d\n", ans); return ans; }

8 Case study 1 Problem statement: A palindrome consists of a word or deblanked, unpunctuated phrase that is spelled exactly the same when the letters are reversed. Write a recursive function (in C) that returns a value of 1 if its string argument is a palindrome. Notice that in palindromes such as madam i'm adam (madamimadam), level, deed, and sees, the first letter matches the last, the second matches the next-to-last, and so on.

9 Case study 2 Problem statement: Implement the recursive version of binary search algorithm.

10 10 References J.R. Hanly & E.B. Koffman, Problem Solving and Program Design in C (6 th Ed.), Addison- Wesley, 2010 P.J. Deitel & H.M. Deitel, C How to Program (5 th Ed.), Pearson Education, Inc., 2007.


Download ppt "Recursion (II) H&K Chapter 10 Instructor – Gokcen Cilingir Cpt S 121 (July 25, 2011) Washington State University."

Similar presentations


Ads by Google