1 / 5

Mutual Recursion and Recursion with helper methods

Mutual Recursion and Recursion with helper methods. Richard Gesick. Mutual Recursion. So far we have only considered recursive methods that call themselves. Another type of recursion involves methods that cyclically call each other. This is known as cyclical or mutual recursion.

waylon
Download Presentation

Mutual Recursion and Recursion with helper methods

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Mutual Recursion and Recursion with helper methods Richard Gesick

  2. Mutual Recursion • So far we have only considered recursive methods that call themselves. Another type of recursion involves methods that cyclically call each other. This is known as cyclical or mutual recursion

  3. Mutual Recursion • . In the following example, methods A and B are mutually recursive.   void A(int n) {    if (n <= 0) return;   n--;   B(n); }   void B(int n) {   if (n <= 0) return 1;   n--;   A(n); }

  4. Recursive Helper Methods • Sometimes, to make programming easier for the “public view”, we use helper methods to hide our implementation of the solution.  When we use this technique with a recursive method, we actually have to figure out a recursive solution to a similar problem instead of the original problem.  • The main reasons for helper methods are: • To change the value of an object reference • To hide implementation details • To enhance efficiency

  5. Helper methods • public int sum( int n) { if( n== 1) return 1; else return n + sum(n-1); } • private int sum(int n) { if( n==1) return 1; else return n + sum(n-1); } public intgetSum(int n) { if( n > 0) return sum(n); }

More Related