50 likes | 231 Views
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.
E N D
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
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); }
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
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); }