0

I am having a hard time understanding the code below. Once the IF statement counts down to 0 it stops, but then "cout<<endl<<n;" starts running and counting until 2.

void guess(int n){ 
     if(n > 0){ 
     cout << n; 
     n--; 
     guess(n); 
     cout << endl << n; 
  } 
} 

int main(){
    guess(3); 
}
// The result is "321
                  0
                  1
                  2"

WHY it counts backwards from 0 to 2 after the end of the IF statement??? I tried debugging it to closely see the process of recursion but it did not help either.

Tilek1990
  • 23
  • 3
  • Do you understand the concept of Stack? Before being able to grasp how recursion works you will need to make sure to understand stacks well. – skyCode Oct 09 '22 at 04:34
  • Handy tool: If you step through the program line by line with a debugger you'll be able to see exactly how the code works. – user4581301 Oct 09 '22 at 04:45

1 Answers1

0

When guess call inside guess second cout is don't run yet, and first this block will execute in last recursion step (because call guess(0) do nothing). And you have this:

54321 - execution of cout << n

0 - execution of cout << endl << n

1

2

3

4

TheRyuTeam
  • 233
  • 1
  • 6