Recursion means you call the function inside that function and resolve it from the back, since you don’t have a value until resolving the last function call, which will end in a value.
Calls like this could look like:
int factorial(int number) {
if (number > 1) {
return number * factorial(number – 1);
} else {
return 1;
}
}
Iterative this would look like:
int factorial(int number) {
int factorial = 1;
while(number > 0) {
factorial = factorial*number;
number–;
}
return factorial;
}
Both functions do the factorial (in math it would be number!).
So for example: 5! = 5*4*3*2*1 = 120
Recursion will do in order 1*2*3*4*5 = 120 and the iteration will do 5*4*3*2*1 = 120.
As you can see, the iterative approach has an iteration (like the name suggests) using a while loop. The recursion example will use “it’s own” until you reach the end up in a value and then goes from bottom up and resolves the stack to evaluate the result.
Latest Answers