Recursion is really easy to understand. It is essentially a function calling itself. Just imagine writing a function that calculates the factorial of a number n (n!
). Lets see how it would expand for 4!
. Remember that 1! = 1
.
(factorial 4)
(4 * (factorial 3))
(4 * (3 * (factorial 3)))
(4 * (3 * (2 * (factorial 1))))
(4 * (3 * (2 * 1)))
(4 * (3 * 2))
(4 * 6)
(24)
The factorial keeps multiplying the current number by the factorial of the natural number one less than it (4 * 3!
) until it reaches its terminating condition (1! = 1
) which then allows all the functions before it to evaluate the return statement (n * factorial(n-1)
) and pass it back up the stack.
Translated to Java code:
int factorial(int n)
if(n == 1)
return 1;
else
return n * factorial(n-1);
A recursive function takes an input and determines if it should stop (here, if n == 1
) or perform an operation (here, multiplying n by something) and passing the remainder of the argument (here, all of the numbers less than n, and >= 1) to itself to do it all over again until it stops.
Every time you call a function, the computer goes off to evaluate that function for the arguments you passed in and then when that is done, it returns back to the original function call and returns a value. So when you call return n * factorial(n-1)
the computer stops here to go evaluate factorial(n-1)
and so on and so on until something different comes back (1
) which then allows all of the stopped processes to return a value.
hey hey this is so funny ...! ok, what if i want to calculate an equation by using recursion as it contains special characters. SPECIAL CHARACTERS think of it ItIsPurelyAsTrIng So it has some ascii value and the recursion stops only when 1 has reached. i don't know what i'm asking.