+ 1
Recursion question
I have one ex. of the tut. : https://code.sololearn.com/865/#cs Here the Method Fact() is called with the int 6, alright until here. Then the Method returns num (in this ex.6) multiplied with the method with int 5. that means that the return doesnt ends because the method is called and it begins again. But at the 1. it would be 6 * ..., but at the 2.call of Fact() it would be 5*...., and at the end 2*1. and all returns havent been closed and wouldnt be returned all factors until 720?
1 Respuesta
+ 1
Hi this can be difficult to get your head round so I have tried to write each of the steps that happen when this code is run, I hope it helps explain what is happening.
1st Call: Fact(6)
6 != 1
2nd Call: Fact(5) ...(6-1)
5 != 1
3rd Call: Fact(4) ...(5-1)
4 != 1
4th Call: Fact(3) ...(4-1)
3 != 1
5th Call: Fact(2) ...(3-1)
2 != 1
6th Call: Fact(1) ...(2-1)
1 == 1 so return 1.
Now we go back up the stack...
5th Call: Fact(2)
return from 6th call was 1.
So return 2 x 1;
4th Call: Fact(3)
return from 5th call was 2.
So return 3 x 2;
3rd Call: Fact(4)
return from 4th call was 6.
So return 4 x 6;
2nd Call: Fact(5)
return from 3rd call was 24;
So return 5 x 24;
1st Call: Fact(6)
return from 2nd call was 120;
So return 6 x 120;
Result = 720