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?

13th Oct 2018, 9:43 PM
Игорь Сакуев
Игорь Сакуев - avatar
3 Answers
+ 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
14th Oct 2018, 1:27 AM
qwerty
qwerty - avatar
+ 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
14th Oct 2018, 5:52 AM
Anna
Anna - avatar
0
Lol. and then factorial function return 1. Main gives 120. Realy???
13th Oct 2018, 9:51 PM
Игорь Сакуев
Игорь Сакуев - avatar