Java Recursion


Java Recursion

Recursion is a way to make the call work itself. This process provides a way to break down complex problems into simple problems that are easy to solve.

Repetition can be difficult to understand. The best way to find out how it works is to try it.


Recursion Example

Combining two numbers together is easy to do, but adding a range of numbers is very complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into a simple task of adding two numbers:


Example

Use recursion to add all of the numbers up to 10.

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;
              }
            }
          }

Example Explained

When the sum() function is called, add the parameter k to the value of all numbers less than k and return the result. If k becomes 0, the function simply returns 0. If applicable, the program follows these steps:


10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Since the function does not call itself when k is 0, the system stops there and returns the result.


Halting Condition

Just as loopholes can get in the way of endless looping, repetitive tasks can get into the problem of endless looping. Endless repetition is when the work does not stop driving itself. Every repetitive task should be in a standing position, which is when the task stops driving itself. In the previous example, the setting condition is when the parameter k becomes 0.

It helps to see various examples to better understand the concept. In this example, the function adds a numerical range between the beginning and the end. The stopping point for this repetitive task is that the end is even greater than the start:


Example

Use recursion to add all of the numbers between 5 to 10.

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