A recursive method calls itself. Recursion has two parts: the base case and the recursive step. To solve a problem recursively you must break down the problem to a smaller version of itself in the recursive step. Eventually you will break down the problem enough to reach the base case.


public static int factorial(int n){
   if(n == 0){
        return 1;
       return n * factorial(n-1);

Explanation of Code

This code returns the factorial of n. This code works as follows. n! is just n multiplied by the factorial of n - 1. For example, 7! = 7 * 6!. But the code does not have a value for 6!. But it knows that 6! = 6 * 5!, and so on until it reaches zero. 0! is one, and 1! is 1* 0!, which is one. And 2! is 2* 1!, which is two. And the code continues until it reaches 7.


Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License