+ 1

What is the output of this and how?

int foo(int x){ if(x<=1) return 1; return foo(x-1)*x; } int main(){ cout<<foo(4); }

27th Sep 2021, 3:34 PM
Supriya
Supriya - avatar
3 Respuestas
+ 2
This will return 4! = 24 This is an example of recursive function, which means that it calls itself. So here is how that works: Foo(4) is called from main Foo(3) is called from Foo(4) Foo(2) is called from Foo(3) Foo(1) is called from Foo(2) In Foo(1) X==1 so that function returns 1 back to foo(2) Then foo(2) returns 1*2=2 to foo(3) Foo(3) returns 2*3=6 to foo(4) Foo(4) returns 6*4=24 back to main function where it gets printed.
27th Sep 2021, 3:42 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 2
It's like doing (3 x 2 x 1) x 4 When the recursion base case is reached (<x> <= 1) it returns 1. Before it did, it does multiplication of number sequence - 3 then 2 Recursion is indeed tricky to explain though. Hope I wasn't mistaken ...
27th Sep 2021, 3:49 PM
Ipang
+ 2
Ok thank u for the explanation 👍
27th Sep 2021, 3:50 PM
Supriya
Supriya - avatar