function a = fct(n)if n==1a = 1; else a = n*fct(n-1);endend
This is how I picture it... Below is a recursion/factorial diagram that shows the cascading effect of the recursive calls. At the deepest recursive call fct(1)
is evaluated which is equal to 1 given by the first if statement. Each recursive call is therefore defined by a deeper recursive call. I typically like to decompose the recursive function until reaching its terminating case. I guess a way to phrase it is "a function within function" not so much of a loop.
Where, fct(1) → 1
format compactfct(5)function a = fct(n)if n == 1a = 1;elsea = n*fct(n-1);fprintf("%d\n",a);endend
2624120ans =120
format compactfct(5)function a = fct(n)if n > 1a = n*fct(n-1);elsea = n;endend