Recursion

A recursive function solves a particular problem by calling a copy of itself and solving smaller sub problems of the original problems. Many more recursive calls …

1): Terminates when the base case becomes tr…

3): Every recursive call needs extra space in the …

2): Used with functions

4): Smaller code size

Rules of Recursion:-

1). Method calling itself.

2). Method should be needed.

3). Must pass the arguments.

4). Must return statement

5). Must have If statement

Need of Recursion

Recursion is an amazing technique with the help of which we can reduce the length of our code and make it easier to read and write. It has certain advantages over the iteration technique which will be discussed later. A task that can be defined with its similar subtask, recursion is one of the best solutions for it. For example; The Factorial of a number.

Sample Program of Recursion:-

int fact(int n)
{
    if (n < = 1) // base case
        return 1;
    else    
        return n*fact(n-1);    
}

Factorial Program using Recursion:-

public class Fact
{
 
  // Factorial function
  static int f(int n)
  {
 
    // Stop condition
    if (n == 0 || n == 1)
      return 1;
 
    // Recursive condition
    else
      return n * f(n - 1);
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int n = 5;
    System.out.println("factorial of " + n + " is: " + f(n));
  }
}
 

Output Screenshot:-

Reference :

geeksforgeeks

Leave a Reply

Create your own website, free on WordPress.com.Create your own website.
Start free