#include <stdio.h> void CntTo3(int); void CntTo2(int); void CntTo1(int); int main() { int n; CntTo3(3); return 0; } void CntTo3(int p) { CntTo2(p-1); printf("%d\n",p); } void CntTo2(int p) { CntTo1(p-1); printf("%d\n",p); } void CntTo1(int p) { printf("%d\n",p); } 

After compilation, the answer is shown as -

 1 2 3 

It turns out that in order to output 1 in the function CntTo3 , you need to execute the function CntTo2 , which will be 2, well, and CntTo1 already outputs without calculations 3. Did I understand correctly? If so, why is CntTo3(3) defined in main() CntTo3(3) and why is the variable n ?

    2 answers 2

     int main() { int n; CntTo3(3); return 0; } void CntTo3(int p) { CntTo2(p-1); printf("%d\n",p); } void CntTo2(int p) { CntTo1(p-1); printf("%d\n",p); } void CntTo1(int p) { printf("%d\n",p); } 

    Let's just substitute the code instead of calling:

     int main() { int n; CntTo2(2); printf("%d\n",3); return 0; } void CntTo2(int p) { CntTo1(p-1); printf("%d\n",p); } void CntTo1(int p) { printf("%d\n",p); } 

    Next substitution:

     int main() { int n; CntTo1(1); printf("%d\n",2); printf("%d\n",3); return 0; } void CntTo1(int p) { printf("%d\n",p); } 

    And last:

     int main() { int n; printf("%d\n",1); printf("%d\n",2); printf("%d\n",3); return 0; } 

    So clearer?

    The variable n does not work anywhere (by the way, the compiler should warn about this).

    • void CntTo3(int); void CntTo2(int); void CntTo1(int); That is, this code calls functions before main () and determines the order of the call? - Konstantin
    • This code simply DECLARES that there are such functions with such names. You can transfer the definitions to the place of declarations (with function bodies going after main() ), and everything will work. It's just that the compiler needs ads, so that it knows that there is such a function. And the call sequence is defined in main() . CntTo3 is CntTo3 — so instead of calling, I can simply write down its code, what it does — and this is a call to CntTo2 and the output of a triple. And so on .. - Harry
    • Understood, Thank you so much! - Konstantin

    Here is the situation: calling a function and printing on the screen plays a big role.
    If you swap places for calling a function and displaying it, you’ll get 3,2,1

    Here the main order.

    First, another function is called, and then the current value is displayed.
    If you swap:

     void CntTo3(int p) { printf("%d\n",p); CntTo2(p-1); } void CntTo2(int p) { printf("%d\n",p); CntTo1(p-1); } void CntTo1(int p) { printf("%d\n",p); } 

    Then it will turn out 3.2.1

    and this is not recursion. Recursion is when a function calls itself.

     void CntTo3(int p) { if (p>1) CntTo3(p-1); printf("%d\n",p); } 

    try this too.