+ 1

Function problem

#include <iostream> using namespace std; int foo (int x) { // becomes int foo (int 4), or int foo (4) --> same thing right? if (x<=1) // this evaluates to false return 1; return foo (x-1)*x; // is the value 4 assigned to x-1 or to x? } // are we dealing with a recursion or no? int main () { cout << foo(4); } // How does this output evaluate 24 (the correct output)? // I calculated it to be 12... by assigning 4 to x in line ' return foo (x-1)*x; '

30th Jul 2020, 5:41 AM
Solus
Solus - avatar
2 odpowiedzi
+ 2
Yes it is a recursion... When first the function executes We get, foo(3)*4 and for second iteration foo(2)*3*4 And for third iteration foo(1)*2*3*4 since we get x= 1 then if condition get true and returns 1 So now we have 1*2*3*4 results to 24
30th Jul 2020, 6:09 AM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
+ 2
Solus you are not returning (x-1)*x instead you are returning " foo(x-1)*x " Just like Мг. Кнап🌠 already said, this process is known as recursion (when a function calls itself). This function is recursively calculating factorial of a number.
30th Jul 2020, 6:14 AM
Arsenic
Arsenic - avatar