Login    New User    Forgot Password    Help      

Recursion

Java Tutorials

Simply put, recursion is when a function calls itself. That is, in the course of the function definition there is a call to that very same function. At first this may seem like a never ending loop, or like a dog chasing its tail. It can never catch it. So too it seems our method will never finish. This might be true is some cases, but in practise we can check to see if a certain condition is true and in that case exit (return from) our method. The case in which we end our recursion is called a base case . Additionally, just as in a loop, we must change some value and incremently advance closer to our base case.

Example

class recursion
{
        void abc(int n)
        {
        System.out.println(n);
        if(n<10)
                {
                n++;
                abc(n);       
                }
       
        }
}
class rec
{
public static void main(String args[])
{
recursion r1=new recursion();
r1.abc(5);

}
}

Output

e:\java\java rec

5

6

7

8

9

10

Java Tutorials