Saturday, July 15, 2023

RECURSION

 

RECURSION

RECURSION

Recursion is a programming technique where a function calls itself. This may sound confusing, but it can be used to solve some problems that would be difficult or impossible to solve with other techniques.

In Java, recursion is implemented using the return statement. The return statement can be used to return a value from a function, or it can be used to call the function recursively.

public class Factorial {

  public static int factorial(int n) {

    if (n == 0) {

      return 1;

    } else {

      return n * factorial(n - 1);

    }

  }

  public static void main(String[] args) {

    System.out.println(factorial(5)); // 120

  }

}

This code defines a function called factorial() that calculates the factorial of a number. The factorial of a number is the product of all the positive integers less than or equal to that number. For example, the factorial of 5 is 120.

The factorial() function is recursive. It calls itself to calculate the factorial of the number minus 1. The base case of the recursion is when the number is 0. In this case, the function simply returns 1.

The main() method of the code calls the factorial() function with the number 5. The factorial() function then recursively calculates the factorial of 5 and returns the value 120.

comparison of recursive and iterative methods in Java:

Recursive Method

Iterative Method

A method that calls itself.

A method that uses a loop to repeat a block of code.

Can be used to solve problems that are naturally recursive.

Can be used to solve problems that are not naturally recursive.

Can be more concise and elegant than iterative methods.

Can be easier to understand and debug than recursive methods.

Can be slower than iterative methods.

Can be faster than recursive methods.

Uses more stack space than iterative methods.

Uses less stack space than recursive methods.

example of a recursive method in Java:

public static int factorial(int n) {
    if (n == 0) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

example of an iterative method in Java:

public static int factorial(int n) {
    int factorial = 1;
    for (int i = 1; i <= n; i++) {
        factorial *= i;
    }
    return factorial;
}

No comments:

eLearning and Blackboard

  IT professional, U bring a unique set of skills and expertise that can greatly contribute to the successful development and implementati...