There is a function that calls itself, that is, recursive. Suppose n = 5. It is necessary to calculate the sum of the elements that appear on the console (but this is just a word).

At first, everything seems to be clear. The sequence will be this 5 4 3 2 1 0. I can’t understand further, in the debug it looks like this - 0 does not fit the condition and naturally doesn’t fit into the body if, but when it reaches the last bracket, it goes in the opposite direction (i.e. the functions do not start from the beginning, but from the end) In the photo, the sequence of calls and somehow falls into if and n = 1. How does this happen? I can not understand

static public void F(int n) { Console.Write(n + " "); if (n > 0) { F(n - 1); F(n - 3); } } 

enter image description here

    1 answer 1

    This is the essence of recursion, it calls itself, then returns control, but to the place where it was called

    Therefore, it turns out that at first the function goes deep into and reaches n equal to 0 , then returns control to the previous function, where n was still equal to one and enters the function F(n-3); where it becomes equal to -2 , then returns the value of the function, where n is one, then it exits to and from it, where it returns control of the function, where n is 2 , etc.

    A good way to understand recursion is to bypass the tree in depth.