RECURSIVE FUNCTIONS

RECURSIVE FUNCTIONS:
A function that calls itself is called a recursive function. A recursive function must definitely have a condition that exits from calling the function again. hence there must be a condition that calls the function itself if that condition is true.if the condition is false then it will exit from the loop of calling itself again.

recursion
recursion in Java

Example for Recursion:

import java.util.*;
class Factorial {
    static int factorial( int n ) {
        if (n != 0)
            return n * factorial(n-1); // recursive call
        else
            return 1;
    }
    public static void main(String[] args) {
        int number = 5, result;
        result = factorial(number);
        System.out.println(number + " factorial = " + result);
    }
}

OUTPUT:

 5 factorial = 120

Translate »