11/10/2014

How Recursion Work In Java

Recursion means calling a function by himself again and again until base case. In this simple Program we use recursion in recursive function. In main class just initialize a variable and then pass through the Parameter of function. In function we can decrements the value of that variable by using the recursive call function. And when the value of first initialization is equal to the condition then Program terminates.

Source Code


public class Java_Recursive {
    public static void main(Stringargs[])
    {
        int rec = 10;
        rec = recursive(rec);
         System.out.println(""+rec);
       
    }
    public static int recursive(intrec)
    {
        if(rec==5)
        {
             System.out.println(""+rec);
             return 0;
        }
        else
        return recursive(rec-1);               
    }
}


Output of the Program 

how recursion work in java


No comments:

Post a Comment