Recursion

Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.

A condition must be specified to stop recursion; otherwise it will lead to an infinite process.

In case of recursion, all partial solutions are combined to obtain the final solution.

Advantages:

i. The main benefit of a recursive approach to algorithm design is that it allows programmers to take advantage of the repetitive structure present in many problems.

ii. Complex case analysis and nested loops can be avoided.

iii. Recursion can lead to more readable and efficient algorithm descriptions.

iv. Recursion is also a useful way for defining objects that have a repeated similar structural form.

 Disadvantages:

i. Slowing down execution time and storing on the run-time stack more things than required in a non recursive approach are major limitations of recursion.

ii. If recursion is too deep, then there is a danger of running out of space on the stack and ultimately program crashes.

iii. Even if some recursive function repeats the computations for some parameters, the run time can be prohibitively long even for very simple cases.

Example,

public class Main {
  public static void main(String[] args) {
    int result = sum(10);
    System.out.println(result);
  }
  public static int sum(int k) {
    if (k > 0) {
      return k + sum(k - 1);
    } else {
      return 0;
    }
  }
}

Reference.

https://www.w3schools.com/java/tryjava.asp?

https://www.javatpoint.com/recursion-in-java

Leave a comment

Design a site like this with WordPress.com
Get started