1 / 5

Recursion

Recursion. Brian Toone 10/14/09. Recursion. When a method calls itself Example int factorial(n) { if (n<=1) return 1; else return n*factorial(n-1); }. Properties of recursion. All recursion must end Base case The condition which terminates the recursion

erelah
Download Presentation

Recursion

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. Recursion Brian Toone 10/14/09

  2. Recursion • When a method calls itself • Example int factorial(n) { if (n<=1) return 1; else return n*factorial(n-1); }

  3. Properties of recursion • All recursion must end • Base case • The condition which terminates the recursion • Each recursive call should make progress towards base case • Factorial – the base case occurs when n <= 1 int factorial(n) { if (n<=1) return 1; else return n*factorial(n-1); }

  4. Example • Display all possible orderings of the letters in the word “carbon” • Recursive solution • Concatenate ‘c’ to the beginning of each ordering returned from a recursive call made on “arbon” • Concatenate ‘a’ to the beginning of each ordering returned from a recursive call made on “crbon” • The recursive call is made to obtain the orderings of the subwords “arbon”, “crbon”, “cabon”, “caron” • Base case: only one letter - simply return it

More Related