Recursion | Sololearn: Learn to code for FREE!

0

Recursion

How it works when it print just one responce? Look: it take 5, multiply it on 4 and ends when return to main() and then starts with 4 to argument again and then multiply in 3 and the same? Why it prints once in main? Explain me PLEASE! int factorial(int n) { if (n==1) { return 1; } else { return n * factorial(n-1); } int main() { cout << factorial(5); } } Maybe while recursion till work function are not return nothing? Then how it gives 120 but last myltiply num or first?

10/13/2018 9:43:00 PM

Игорь Сакуев

3 Answers

New Answer

+3

5 * factorial(5-1) 4 * factorial(4-1) 3 * factorial(3-1) 2 * factorial(2-1) 1 2 * facotrial(2-1) = 2 * 1 3 * factorial(3-1) = 3 * 2 * 1 4 * factorial(4-1) = 4 * 3 * 2 * 1 5 * factorial(5-1) = 5 * 4 * 3 * 2 * 1 = 120

+1

factorial(5) is called from main(). So only the return value from factorial(5) will be returned to main(). When factorial() calls itself recursively, the return values for factorial(4), factorial(3) etc. are returned to the function factorial() itself

0

Lol. and then factorial function return 1. Main gives 120. Realy???