Java Recursion

Java Recursion

Hello readers, in today’s topic, we will discuss what recursion is in Java. These are fundamental concepts that must be remembered before writing a Java program. Before these, we also discussed Java Method Overloading 2022 & Loop Control in Java 2022, if you don’t know Hurry up Now! Previously we also briefly described various Java topics such as Operator in Java, Data types of Java, Difference between C++ & Java, and many more which are helpful for your better understanding. So without wasting time let’s dive into our topic:

The function called itself repeatedly is known as Recursion.

This technique breaks down the problem into a small problem that is easy to solve.

It may be a little bit difficult to understand, but it completes the code difficult to understand.

Syntax:-

returntype methodname(){  
//code to be executed  
methodname();//calling same method  
}  

Recursion Example

Recursion is helped to solve the problem in an easy way so we take the example. Adding two numbers is easy to do but adding a range of numbers that is 0 to 10 is quite difficult so we see how recursion will help to solve the problem.

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() the function is called, it adds a parameter k to the sum. if the number is smaller the k gives the result. When k becomes 0, the function just returns 0.

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

Output:-

55

we are discussing another example for better understanding.

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

Output:-

45

For more read with us Oraltadalafil

Read our previous post

Leave a Comment

%d bloggers like this: