Question about recursion

+1 Pavel Andrei · August 14, 2016
So recently i watched Bucky's 31st tutorial on c++ programming and i know how to write the code,but i don't understand the logic behind it,i don't know what each line of code does.So,i have a couple of questions:

Why do we type return 1 ?
Why when the function ends it gives us 5x4x3x2x1?Because when we type return x*factorialFinder(x-1); i think it would go like this: 5x4 and then 4x3         3x2          2x1

Post a Reply

Replies

Oldest  Newest  Rating
+1 Scott Walker · August 14, 2016
Question about recursion? (sorry couldn't resist :-))
0 Pavel Andrei · August 29, 2016
Ok,so i understood the return 1 part,but still,i don't understand why it gives us 5x4x3x2x1
When i said that i think it would go like this: 5x4    4x3      3x2      2x1 you guys said that that's right,but i still don't understand why in the end they all get to multiply and basically give us 5x4x3x2x1 (120)
I don't understand the steps that the program goes through to get to 5x4x3x2x1 
+1 Adeel Salim · September 3, 2016
Pavel i am also confused about it. 
0 Pavel Andrei · September 3, 2016
Ty
0 Berkay Çağlı · September 28, 2016
"Ok,so i understood the return 1 part,but still,i don't understand why it gives us 5x4x3x2x1
When i said that i think it would go like this: 5x4    4x3      3x2      2x1 you guys said that that's right,but i still don't understand why in the end they all get to multiply and basically give us 5x4x3x2x1 (120)
I don't understand the steps that the program goes through to get to 5x4x3x2x1 "

Well the reason is that every time you want factorialFinder function, that expression is changed by the value the function returns. 

let's assume that you want 4 factorial
first
return 4*factorialFinder(3)
factorialFinder(3)= 3*factorialFinder(2)
factorialFinder(2)= 2*factorialFinder(1)
and fatorialFinder(1) = 1 so now you can start replacing values
facfinder(2) = 2*1
facfinder(3) = 3*2*1
facfinder(4) = 4*3*2*1

and that is why it works :)
  • 1

C++

131,187 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator