Thread: Recursion

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    6

    Question Recursion

    I need some help on my program. By using recursion, i have to write a program that give the output in vertical order... e.g. if i input 1234, the ouput will be:
    1
    2
    3
    4
    I don't know how the structure works, and i have no idea how to begin...

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    61
    hint: you will need '/' and '%' operators.

    '/' will chop the number down by tenths.

    1234 / 10 = 123 (note, really = 123.4, but .4 chopped off since dealing with int here)

    '%' will extract the right most digit from the number.

    1234 % 10 = 4.

    just add some recursion and you solved it!

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    6

    Post

    This is a program which is backwards.. how can i reverse it?



    #include <iostream>
    using namespace std;

    void printForwards( int );

    int main( void )
    {
    int num;

    cout << "Please enter a positive integer: " << endl;
    cin >> num;

    cout << "Testing printForwards" << endl;
    printForwards( num );


    return 0;
    }
    void printForwards( int num )
    {
    if( num > 0 )
    {
    cout << ( num % 10 ) << endl;
    printForwards( num / 10 );
    }
    }

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Study the difference between

    cout << ( num % 10 ) << endl;
    printForwards( num / 10 );

    and

    PrintForwards( num / 10 );
    cout << ( num % 10 ) << endl;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    6

    Cool thank you

    thank u for ur help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 09:45 PM
  2. convert Recursion to linear can it be done
    By umen242 in forum C++ Programming
    Replies: 2
    Last Post: 10-15-2008, 02:58 AM
  3. Recursion... why?
    By swgh in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2008, 09:37 AM
  4. a simple recursion question
    By tetra in forum C++ Programming
    Replies: 6
    Last Post: 10-27-2002, 10:56 AM
  5. To Recur(sion) or to Iterate?That is the question
    By jasrajva in forum C Programming
    Replies: 4
    Last Post: 11-07-2001, 09:24 AM