output is: 0 0...">

Recursion and pre-reduction operator

I have this function:

void m(int n)
{
    if(n > 0)
      m(--n);
      cout << n << " "; //for n = 5 --> output is: 0 0 1 2 3 4
}

I have a problem understanding how this works. For instance:

n (input) = 5

output: 0 0 1 2 3 4

My question is: Why does it show zero twice?

When I add the brackets as follows:

void m(int n)
{
    if(n > 0)
    {
        m(--n);
        cout << n << " "; // now, it shows 0 1 2 3 4 (n = 5)
    }
}

So, what brackets cause in this code that "0" exists only once?

And when I change the pre-decrement (-n) to the post-decrement (n--), it shows nothing. Why?

Can someone help me understand how this works?

+4
source share
2 answers

: ++, if, .

:

if(x > 0)
   cout << 1;
   cout << 2;

cout << 2 x

:

if(x > 0)
{
  cout << 1;
  cout << 2;
}

else , .

: m(n--), 5, n ( ). , , m (5) . ( , , , , )!

, !

+7

, Python, if . C ( ++, #, Java ) - ( ;), { }. 1- cout << n << ... n. if(n > 0)

+4

All Articles