Java Method Recursion

Introduction

Java supports recursion.

Recursion allows a method to call itself.

A method that calls itself is said to be recursive or a recursive method.

The following code uses recursion to calculate the factorial of a number.

The factorial of a number N is the product of all the whole numbers between 1 and N.

For example, 3 factorial is 1 × 2 × 3 ×, or 6.

Here is how a factorial can be computed by use of a recursive method:

// A simple example of recursion.
class Factorial {
  // this is a recusive function
  int fact(int n) {
    int result;/*from w  w  w  .  ja va  2  s  . com*/

    if(n==1) return 1;
    result = fact(n-1) * n;
    return result;
  }
}

public class Main {
  public static void main(String args[]) {
    Factorial f = new Factorial();

    System.out.println("Factorial of 3 is " + f.fact(3));
    System.out.println("Factorial of 4 is " + f.fact(4));
    System.out.println("Factorial of 5 is " + f.fact(5));
  }
}

When fact() is called with an argument of 1, the function returns 1.

For value other than 1, it returns the product of fact(n-1) × n.

This process repeats until n equals 1.

The following code uses recursive method printArray() to print the first i elements in the array values.

// example that uses recursion.
class RecTest {/*from w w w . java2  s.  c  o  m*/
  int values[];

  RecTest(int i) {
    values = new int[i];
  }

  // display arrary -- recursively
  void printArray(int i) {
    if(i==0) return;
    else printArray(i-1);
    System.out.println("[" + (i-1) + "] " + values[i-1]);
  }
}

public class Main {
  public static void main(String args[]) {
    RecTest ob = new RecTest(10);
    int i;

    for(i=0; i<10; i++) ob.values[i] = i;
    
    ob.printArray(10);
  }
}



PreviousNext

Related