R
R
RomKing2021-01-29 16:18:40
IT education
RomKing, 2021-01-29 16:18:40

Why does executing a recursive method in C# add an extra rung on execution?

Greetings. Ladies and gentlemen programmers, please help me to understand the following
:

static void Method(int value) 
{
   value++;   
   Console.WriteLine($"A = {value}");                  

    if (value < 5)                           
           Method(value);

   Console.WriteLine($"B = {value}");
}

 static void Main(string[] args)
 {
   Method(2);
 }


The output to the console is as follows:
A = 3
A = 4
A = 5
B = 5
B = 4
B = 3

For the life of me, I can’t get to the bottom of what the devil appears in the last line of the console?
Following the sequence of steps, it turns out like this:
1. value = 2,
2. value is incremented (now 3). Printed to the console: A=3
3. The If block is executed - the method is called,
4. In this repeatedly called method, the value is incremented and now value = 4. Printed to the console: A=4
5. The body of the If block is executed again - the method is called.
6. Value is incremented and output to the console: A=5
7. Further if is not executed, we skip and get to the second Console.WriteLine construction. The following is displayed on the console: B=5


I don’t understand what is happening next. It seems that the program should complete its work on this, all method calls have ended, but it returns to the method two more times. I tried to explain the appearance of a four after five by hook or by crook, but with a triple it’s generally a disaster ...
In the second case, I explained the four to myself by the fact that after the complete completion of the if operation, we get, with the four saved earlier in the external method, into the last line of the Console .WriteLine. But C grade where does it come from, if it's wrong????
I really hate all three now)

Ps Doperlo from the 10th time. Moreover, the 11-year-old son understood the first time, he just could not explain to me))). Now it is clear why employers prefer to hire young programmers. At 40 years old, the brain is not so smart, especially if before that 25 years old kicked the bulldozer (((

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
HemulGM, 2021-01-29
@RomKing

Because you don't exit the method if the condition is not met

if (value < 5)                           
           Method(value)
else return;

I don't understand what comes next.

Then you exit from all Method methods, and each exit from such a method ends with you
Console.WriteLine($"B = {value}");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question