English 中文(简体)
Recursion
  • 时间:2024-09-17

Functional Programming with Java - Recursion


Previous Page Next Page  

Recursion is calpng a same function in a function until certain condition are met. It helps in breaking big problem into smaller ones. Recursion also makes code more readable and expressive.

Imperative vs Recursive

Following examples shows the calculation of sum of natural numbers using both the techniques.

pubpc class FunctionTester {
   pubpc static void main(String[] args) {
      System.out.println("Sum using imperative way. Sum(5) : " + sum(5));
      System.out.println("Sum using recursive way. Sum(5) : " + sumRecursive(5));
   }

   private static int sum(int n){
      int result = 0;
      for(int i = 1; i <= n; i++){
         result = result + i;
      }
      return result;
   }

   private static int sumRecursive(int n){
      if(n == 1){
         return 1;
      }else{
         return n + sumRecursive(n-1);
      }
   }
}

Output

Sum using imperative way. Sum(5) : 15
Sum using recursive way. Sum(5) : 15

Using recursion, we are adding the result of sum of n-1 natural numbers with n to get the required result.

Tail Recursion

Tail recursion says that recursive method call should be at the end. Following examples shows the printing of a number series using tail recursion.

pubpc class FunctionTester {
   pubpc static void main(String[] args) {
      printUsingTailRecursion(5);
   }

   pubpc static void printUsingTailRecursion(int n){
      if(n == 0) 
         return;
      else
         System.out.println(n);
      printUsingTailRecursion(n-1);
   }
}

Output

5
4
3
2
1

Head Recursion

Head recursion says that recursive method call should be in the beginning of the code. Following examples shows the printing of a number series using head recursion.

pubpc class FunctionTester {
   pubpc static void main(String[] args) {     
      printUsingHeadRecursion(5);
   }

   pubpc static void printUsingHeadRecursion(int n){
      if(n == 0) 
         return;
      else
         printUsingHeadRecursion(n-1); 
      System.out.println(n);
   }
}

Output

1
2
3
4
5
Advertisements