Recursion perception help.

Just trying to learn recursion but a little bit confused got loops in my head but it looks like recursion works in a very different way. In the example jumping into c++ its does 123456789987654321 however I have added phase 1 and phase 2 in cout. It seems to loop round on the same statement within the function then it ends when it gets to 1. How does it know how to stop at one as there are no statements to say exit out. And how does it know to go to the next if statement and not loop the 1st cout again?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

#include <iostream>

using namespace std;

void printNum (int num)
{
    // the two calls in this function to cout will sandwich an inner
    // sequence containing the numbers (num+1)...99...(num+1)
    cout << num << " - Phase 1 \n";
    // While begin is less than 9, we need to recursively print
    // the sequence for (num+1) ... 99 ... (num+1)
    if ( num < 9 )
    {
      // cout << num << "\n";
        printNum( num + 1 );
    
    }
    
    cout << num << " - Phase 2 \n";

}

int main ()
{
    printNum( 1 );
}
you do have an exit clause

if ( num < 9 )

after you have called the last cout where num = 8 it will return and go back up the rabbit hole

recursion can be a little hard to grasp a good way to understand whats happening is to put a break point on 'Phase 1' and 'Phase 2' and see how it works.
Last edited on
Thanks for the reply. If that is the exit clause why doesn't it continue looping into into minus values. As sequence is 1234567899887654321. Why doesn't it continue 1234567899876543210-1-2-3-4-5-6-7 etc?

Not done any chapters on debugging or break points yet :\
well do you know how a stack works? well that what a program is made out of. a stack of function calls.

i guess you can look like it as a building in your case it has 8 levels "0 = ground floor" you main function. and every time you go into an other function it you go into an other floor of your program. you can only be on one floor at a time so you ether go up or down. your code does this.

when you call a different function you put it on top of the stack when you return from uit it gets removed. you never go into negative because you cant go further back than main or your program will exit.

if your using visual studio (i imagine other IDE's are the same) then a tutorial like this can help you in explaining how to debug.
https://www.youtube.com/watch?v=C0vDKXIq_9A
Thanks for the help, got to the part of stack, but when I did a cout on every line it shows the trigger point where it kept closing all the other functions. Is quite clear now. Will check out the link you sent.
Topic archived. No new replies allowed.