Recursive Functions in Java


Example: factorial

Java allows a function to use itself. But instead of breaking the definition into cases, just use if-statements to decide among alternatives, and use return statements to say what the answer is.

For example, the following is a definition of the factorial function in Java, using recursion.

  public static long factorial(long n)
  {
    if(n == 1) return 1;
    else return n * factorial(n-1);
  }

Compare that to a definition in Cinnameg using cases. You should see correspondences.

  Define
    case factorial(n) = 1 when n == 1
    case factorial(n) = n * factorial(n-1)
  %Define

Example: greatest common factor

We saw earlier that the greatest common factor function gcf(x, y) can be defined in Cinnameg as follows.

  Define
    case gcf(x,y) = y                  when x == 0
    case gcf(x,y) = gcf(y `mod` x, x)
  %Define
Translating that to Java involves using an if-statement to decide which case to use and converting the `mod` operator to %. Also remember to use return to indicate the answer.
  public static int gcf(int x, int y)
  {
    if(x == 0) return y;
    else return gcd(y % x, x);
  }


More information

Chapter 11 of Savitch and Carrano discusses recursion.


Problems

  1. [solve] Write a Java definition of function sumOdds(n) which produces the sum of the odd integers that are less than or equal to n. Assume that n is an odd positive integer. For example, sumOdds(3) = 1 + 3 = 4, and sumOdds(7) = 1 + 3 + 5 + 7 = 16. Use recursion.

    Assume that the argument has type int and the result also has type int.

    (Hint. For n = 1, just say what the answer is. For n > 1, look for a smaller problem of the same kind that will help you, and use the same function to solve that smaller problem.)

  2. [solve] Function power(x,n) has the following heading.

      public static int power(int x, int n)
    
    Using recursion (and not a loop), write a definition of power so that it returns xn. Assume that n is positive. Use a loop to accumulate the power.

  3. [solve] Using recursion (and not a loop), define function num7s(n) in Java, which takes an integer n and returns the number of 7s in the usual (base 10) representation of n. For example, num7s(2770) = 2 and num7s(99) = 0. Assume that the argument and answer both have type int.

    (Hint. It is obvious what num7s(0) is. For values of n that are greater than 0, look at the rightmost digit of n. If the rightmost digit is a 7, then n has one more 7 then n/10. For example, num7s(3757) is one bigger than num7s(375). If the rightmost digit is not 7, then n has the same number of sevens as n/10.)


Summary

Java allows recursion, in a similar spirit to Cinnameg. But you need to use an if-statement to determine which case to use, and write return to say what the answer is.