Could someone enlighten me?

This is a discussion on Could someone enlighten me? within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> using namespace std; void count ( int x ) { cout << x << endl; if ( ...

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    59

    Could someone enlighten me?

    Code:
    #include <iostream>
    using namespace std;
    void count ( int x )
    {
        cout << x << endl;
        if ( x > 0 ) count ( x - 1 );
    }
    int main()
    {
        count ( 10 );
    }
    There is no problem with the code, I just have a question about it. How come that one counts down from 10 to 0, but if you put the "cout" after the "if," it counts up from 0 to 10? Is it because the condition is stated before the variable? Any help would be appreciated.

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    10s a bit hard lets look at 3

    heres your func swopped...
    Code:
    {    
        if ( x > 0 ) count ( x - 1 );
        cout << x << endl;
    }
    now call with x=3

    x is greater than 0 so count(2)
    in count(2)
    x is greater than 0 so count(1)
    in count(1)
    x is greater than 0 so count(0)
    in count(0)
    x is 0 so cout x
    back in count(1)
    cout x
    back in count(2)
    cout x
    back int count(3)
    cout x

    so u see 0,1,2,3 is printed.

    Now work that thru for the original and you will see why its forwards one way and back the other.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Registered User
    Join Date
    Feb 2005
    Posts
    59
    Oh, wow. Thanks for the help, that solves that question.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21