Recursive function with for

Asked

Viewed 732 times

2

I’m studying recursive functions and I came up with a question when I was looking at some algorithms that use recursive function and for. I decided to create a simple example and print some values on the screen to try to understand how the flow of the program is and ended up wrapping myself even more.

Could someone explain to me what happens?

I’m sorry if I’m not being clear enough, I’m a beginner and I can’t express myself very well.

Follows the code:

function x(n){
    console.log('before , n: ',n);
    if(n === 0)return;
    for(var i = 1; i < 3; i++){  
        console.log('for i:',i);  
        x(n-1);
    }
    console.log('after, n: ',n);
}
x(3);

Follow the print:

inserir a descrição da imagem aqui

3 answers

2


We call recursion or recursion when a function calls itself.

In a recursive function, each call is created in memory a recurrence of the function with "isolated" commands and variables from previous occurrences, so a new scope for each call the function.

At the time the line is executed x(n-1), the current occurrence awaits a response of the new occurrence, that is, it is necessary to wait for the result of the operation x(n-1) for the next operation to be carried out.

In practice the following operations take place:

  1. Call the function x(n).
  2. Print the value of n (before).
  3. Ends the occurrence if n is equal to 0 returning a previous occurrence response (if any).
  4. Cycle for.
  5. Print the value of i.
  6. Starts a new occurrence x(n-1) (return to point 2) and await reply.
  7. Back to the point 4 if i < 3.
  8. Print the value of n (after).

See that at the point 6 we create a new occurrence (n-1) and this causes the current occurrence (n) to wait for the response of the new occurrence before moving to the point 7.

A step by step example for n=2 according to the above scheme:

1. x(2);
2. print "before, n: 2"
3. N > 0
4. For i=1
5. print "for i: 1"
6. x(1) //n-1 em que n=2
    1. Iniciou uma nova ocorrência
    2. print "before, n: 1"
    3. N > 0
    4. For i=1
    5. print "for i: 1"
    6. x(0) //n-1 em que n=1
        1. Iniciou uma nova ocorrência
        2. print "before, n: 0"
        3. N <= 0
        8. print "after, n: 0"
        [Termina a ocorrência]
    4. For i=2
    5. print "for i: 2"
    6. x(0) //n-1 em que n=1
        1. Iniciou uma nova ocorrência
        2. print "before, n: 0"
        3. N <= 0
        8. print "after, n: 0"
        [Termina a ocorrência]
    4. For i=3
    8. print "after, n: 1"
    [Termina a ocorrência]
4. For i=2
5. print "for i: 2"
6. x(1) //n-1 em que n=2
    1. Iniciou uma nova ocorrência
    2. print "before, n: 1"
    3. N > 0
    4. For i=1
    5. print "for i: 1"
    6. x(0) //n-1 em que n=1
        1. Iniciou uma nova ocorrência
        2. print "before, n: 0"
        3. N <= 0
        8. print "after, n: 0"
        [Termina a ocorrência]
    4. For i=2
    5. print "for i: 2"
    6. x(0) //n-1 em que n=1
        1. Iniciou uma nova ocorrência
        2. print "before, n: 0"
        3. N <= 0
        8. print "after, n: 0"
        [Termina a ocorrência]
    4. For i=3
    8. print "after, n: 1"
    [Termina a ocorrência]
4. For i=3
8. print "after, n: 2"
[Termina a ocorrência]

In the above listing, I used the horizontal spaces to simulate a new occurrence of the function x.

If we extract only the lines in which the "print" appears, we will have the following:

before, n: 2
for i: 1
   before, n: 1 
   for i: 1
      before, n: 0
      after, n: 0
   for i: 2
      before, n: 0
      after, n: 0
   after, n: 1
for i: 2
   before, n: 1
   for i: 1
      before, n: 0
      after, n: 0
   for i: 2
      before, n: 0
      after, n: 0
    after, n: 1
after, n: 2

Although the first occurrence is x(2), the after, n: 2 only appears at the bottom of the list because new occurrences have appeared in the middle and fired the console.log before returning a reply.

1

Your doubt is "why the for is saving the value of i = 2 after the base case is hit?"

This is because javascript has function scope instead of block scope, and the initialisation of i is done within the function where the for is, so he knows the value.

  • I’m going to do some research on these terms to learn more. Regarding the flow of the code I have another question, why after the after, n:1, marked as blue in the print, it goes straight to the for instead of going to the before, n:1?

-2

What he’s doing is, for every n, it performs this cycle 3 times. Try changing the cycle for for for (var = i ; i < n ; i++)

  • Another question. From what I read, a recursive function is executed "n" times until it reaches the base case and then returns "n" results by assembling the final result. There are technical terms for me to refer to when a recursive function is "entering" and when it is "returning" ?

  • Ppim, even using i<n my doubt persists. Look at the output: &#xA;before , n: 3&#xA;for i: 1&#xA;before , n: 2&#xA;for i: 1&#xA;before , n: 1&#xA;after, n: 1&#xA;after, n: 2&#xA;for i: 2 &#xA; why the for is saving the value of i = 2 after base case is reached?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.