Why does recursion return to the first function?

Sorry to ask a very simple question about what I have said many times about the argument, I just can not understand the answer. I tried to search the forum for questions already asked on the topic, but did not find the exact answer (or did not understand).

Why does this function print numbers from i to 10 twice when called in a different order? Should I print them in the same order? I continue to hear that recursion works this way: each function in its code calls another identical one that simply applies to a smaller domain until the final condition is met. At this moment, he should return (back) to the original function; this is what I do not understand why it returns (not intended for a syntax call) the main function.

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

Thanks.

+4
2

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

?
, .

+6

, :

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

, i . . "" 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

, , count (i + 1), count (8):

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

:

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);
}

:

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);
}

, . "" i . 10 i , .

+2

Source: https://habr.com/ru/post/1528188/


All Articles