Aspects

Java 8 Onwards

Functional Programming

Streams

Useful Resources

Functional Programming - Recursion



Recursion is calling 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 Approach

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

FunctionTester.java

package com.tutorialspoint;

public class FunctionTester {
   public 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

Run the FunctionTester and verify the 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.

Example - 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.

FunctionTester.java

package com.tutorialspoint;

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

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

Output

Run the FunctionTester and verify the output.

5
4
3
2
1

Example - 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.

FunctionTester.java

package com.tutorialspoint;

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

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

Output

1
2
3
4
5
Advertisements