I'm a starter in C++.
Can someone explain the output of this program ?

# include <iostream>

using namespace std ;

void number ( int a)
{
    if( a < 0 )
     return ;

    else
    {
        cout<< a <<" ";
        number(a - 1);
        cout<< a << " ";
    }


}

int main ()
{
    number(7);

    return 0;
}

Output : 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7

Stack unwinds. When you do a recursive call, it keeps pushing onto the stack. Then you have your return if it's less than 0. At that point, it basically breaks out and starts unwinding and printing every a value that was entered. Well at least that's the way I was taught recursive stuff. Hopefully that's right so that I don't mislead you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.