Java Recursion
Slides provided by the University of Washington Computer Science & Engineering department. Adapted from slides by Marty Stepp, Stuart Reges & Allison Obourn.
Java Recursion Slides provided by the University of Washington - - PowerPoint PPT Presentation
Java Recursion Slides provided by the University of Washington Computer Science & Engineering department. Adapted from slides by Marty Stepp, Stuart Reges & Allison Obourn. Recursion - recursion : The definition of an operation in terms
Slides provided by the University of Washington Computer Science & Engineering department. Adapted from slides by Marty Stepp, Stuart Reges & Allison Obourn.
smaller occurrences of the same problem.
themselves to solve problems recursively
loops)
problems
directly
problem that cannot be directly answered, but can instead be described in terms of smaller occurrences of the same problem
recursive case, but all have at least one of each.
cases.
// Prints a line containing the given number of stars. // Precondition: n >= 0 public static void printStars(int n) { for (int i = 0; i < n; i++) { System.out.print("*"); } System.out.println(); // end the line of output }
public static void printStars(int n) { if (n == 0) { // base case; just end the line of output System.out.println(); } else { // recursive case; print one zero stars System.out.print("*"); printStars(n - 1); } }
public static int mystery(int n) { if (n < 10) { return n; } else { int a = n / 10; int b = n % 10; return mystery(a + b); } }
mystery(648)
mystery(648):
mystery(72):
mystery(9):
public static int mystery(int n) { if (n < 10) { return (10 * n) + n; } else { int a = mystery(n / 10); int b = mystery(n % 10); return (100 * a) + b; } }
mystery(348)
mystery(348):