Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does recursion return to first function?

Sorry for asking a very basic question about an argument already talked about many times, I just can't figure out the answer. I tried searching the forum for already on-topic asked questions but didn't find an exact answer(or didn't understand it).

Why does this function print twice the numbers from i to 10 when called in different order? Shouldn't it print out them in the same order? I keep hearing that this is how recursion works: every function calls in its code another identical one, just applied to a smaller domain until end condition is met. At this point it should go back (backtracking) to the original function; this is what I don't understand, why does it return(not intended as syntax call) to the main function.

void count(int i){
    if(i < 10){
          printf("%d\n", i);
          count(i + 1);
          printf("%d\n", i);
    }
}    

Thank you.

like image 269
user3338768 Avatar asked Feb 14 '23 17:02

user3338768


2 Answers

A call with 7:

count(7)
    output 7
    count(8)
        output 8
        count(9)
            output 9
            count(10)
                end
            output 9
            end
        output 8
        end
    output 7
    end

Why shouldn´t it return?
Each function call will return sometimes, even if it is a recursive function.

like image 73
deviantfan Avatar answered Feb 24 '23 03:02

deviantfan


As with any function call, at the end, execution just starts back up at the next line:

 printf("%d\n", i);
 // into the function
 count(i + 1);
 // out of the function
 printf("%d\n", i);

The important thing to know is that the value of i doesn't get updated. They aren't the same variable. There are ten different 'versions' of i.

 printf("%d\n", i); // i is 3
 count(i + 1);
 printf("%d\n", i); // i is still three, but a version of the function just ran where i is 4

If you imagine just pasting the code in when you see count(i + 1), you get this when expanding count(8):

if(8 < 10){
      printf("%d\n", 8);
      count(8 + 1);
      printf("%d\n", 8);
}

Now paste:

if(8 < 10){
    printf("%d\n", 8);
    if(9 < 10){
        printf("%d\n", 9);
        count(9 + 1);
        printf("%d\n", 9);
    }
    printf("%d\n", 8);
}

And again:

if(8 < 10){
    printf("%d\n", 8);
    if(9 < 10){
        printf("%d\n", 9);
        if(10 < 10){
            // we'll never get here
        }
        printf("%d\n", 9);
    }
    printf("%d\n", 8);
}

This is the code that actually gets run. The 'old' values of i don't change. In the end you have 10 different i variables from all the different times your called the function.

like image 22
Damien Black Avatar answered Feb 24 '23 03:02

Damien Black