Anuj
Anuj

Reputation: 29

Recursion code not working properly

if i remove the comment the code is working fine and if i comment the above lines which are commentd i get an error

package TEST;

class Fact {
    // this is a recursive method
    int fact(int n) {

        // if (n == 1)
        // return 1;
        int result = fact(n - 1) * n;
        return result;

    }

    public static void main(String args[]) {
        Fact f = new Fact();
        System.out.println("Factorial of 7 is " + f.fact(5));
        System.out.println("Factorial of 4 is " + f.fact(4));
        System.out.println("Factorial of 5 is " + f.fact(5));
    }
}

if i remove the comment the code is working fine and if i comment the above lines which are commentd i get an error

Upvotes: 1

Views: 49

Answers (3)

Farvardin
Farvardin

Reputation: 5414

every recursive method must has an exit point, otherwise it run in an infinity loop and doesn't stop never. so your stack be full and you get a Stackoverflow error. see http://en.wikipedia.org/wiki/Recursion for more.

a pretty good example for exit point is ‍spinning top in Inception. if the top stop, Cobb realize that the world is real and if not he is in a dream...

Upvotes: 1

user2120239
user2120239

Reputation: 135

The are two conditions for writing a recursive program. 1. The method calling itself 2. Termination Condition

When u comment the

// if (n == 1) // return 1;

Your code does not know when to terminate and goes into infinite loop hence the error.

Upvotes: 1

Noob
Noob

Reputation: 534

This is the correct recursive method:

int fact (int n)
{
    if (n <= 1) {
        return 1;
    }
    return n * fact (n - 1);
}

In your code you are missing the base case, so it will never stop repeating the method.

Upvotes: 0

Related Questions