Help with recursive function
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10

Thread: Help with recursive function

  1. #1
    Join Date
    Jul 2012
    Posts
    15

    Help with recursive function

    Hi all,

    I am trying to solve the following task:
    -Write a recursive function that prints an integer with decimal separators. For example, 12345678 should be printed as 12,345,678.

    The problem is that I don't know how to modify the integer in such way. I was thinking to convert it into a string, do an algorithm and then turn the string back to integer.

    Please give me some pointers or advises on how to do such modification.

    Thanks in advance.

  2. #2
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,594

    Re: Help with recursive function

    In fact you can't do that at all with the integer variable alone. It stores the integral number as such, but no number formatting information whatsoever. (In fact, even though it's commonly output in decimal for easy reception by humans, the integer varable isn't even decimal.)

    As I understand your assignment, it's asking you to convert the integer into a string in an appropriate way (as you already suggesed) and then print that. You're not even required to preserve the string holding the conversion result; you can simply discard it after printing. And, in particular, you're not required to put the formatted integer value back into the original integer variable, which would be impossible anyway, as pointed out above.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  3. #3
    Join Date
    May 2009
    Posts
    2,413

    Re: Help with recursive function

    Quote Originally Posted by Symus View Post
    -Write a recursive function that prints an integer with decimal separators. For example, 12345678 should be printed as 12,345,678.
    An alternative to building a string is to split the integer numerically and print the parts separated by commas to standard output.

    The standard way to strip off individual digits from a number is to use the % (modulo) operator followed by integer division. For a decimal number (base 10) it would look like this,

    12345678 % 10 = 8
    12345678 / 10 = 1234567

    The number has effectively been split like this,

    12345678 = 1234567*10 + 8

    In this particular case you could instead split into 3-digit chunks,

    12345678 % 1000 = 678
    12345678 / 1000 = 12345

    In the recursive function you decide what number is to be printed and if it's to be preceded by a comma. Then the function calls itself with the reduced number until 0 is reached. Finally when the recursion winds back the actual printing takes place according to the information gathered in each incarnation of the recursive function. In this process the number will be split from right to left and then printed with commas from left to right.

    Phew, it's harder to describe than to code.
    Last edited by nuzzle; April 8th, 2013 at 06:07 AM.

  4. #4
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,594

    Re: Help with recursive function

    Thanks for pointing that out, nuzzle. If I would have to code that and I had the choice, I'd have taken the iterative approach (using the modulo operator, as you described), which would build the string to print back-to-front and only print it when done. However, it was rather late here when I wrote my post, and that probably was the reason why I overlooked that string reversal can elegantly be done implicitly by doing the printing in the recursion unwinding phase.

    The way you describe it no string varable would be required at all, and, strictly speaking, to encapsulate the objective "print that integer" in a black-box funtion taking just the int parameter, for my original approach I'd actually have needed two functions: a recursive one that does the int-to-string conversion and one that takes a single int parameter, calls the recursive conversion function, and eventually prints the conversion result.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  5. #5
    Join Date
    Jul 2012
    Posts
    15

    Re: Help with recursive function

    Hello guys,

    Thanks for your help and suggestions. I managed to solve this task without converting to string. Here is my code if someone is interested:

    Code:
    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    void separate(int number)
    {
        // If the number is below 1000 - print it because it holds exactly or below 3 digits
        if (number < 1000)
        {
            cout << number;
        }
        else
        {
            int temp = number % 1000; // Variable which holds the remainder of the calculation (the last 3 digits of the integer)
            number = number / 1000; // Remove the last 3 digits and pass the remaining of the integer again to the function
            separate(number);
            cout << "," << temp;
        }
    }
    
    int main()
    {
        int input;
        cout << "Enter your number :" << endl;
        cin >> input;
        separate(input);
        cout << endl;
    
        system("PAUSE");
        return 0;
    }

  6. #6
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,594

    Thumbs up Re: Help with recursive function

    I really like your approach for its pragmatism of just separating the thousands groups yourself, leaving conversion of the individual digits inside each group to the C++ standard library. However, your implementation isn't really perfect yet, which you can easily see when you're entering a simple number such as ten millions.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  7. #7
    Join Date
    Apr 1999
    Posts
    27,446

    Re: Help with recursive function

    Quote Originally Posted by Symus View Post
    Hello guys,

    Thanks for your help and suggestions. I managed to solve this task without converting to string. Here is my code if someone is interested:
    What data did you test this with?

    Try 1001. You will see that this doesn't work.

    Regards,

    Paul McKenzie

  8. #8
    Join Date
    Jul 2012
    Posts
    15

    Re: Help with recursive function

    OK, why is this not working?

    And how can I fix it?

  9. #9
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,842

    Re: Help with recursive function

    Code:
    cout << "," << temp;
    cout as default does not output leading 0's to pad fill a number to a set width! You have to tell cout what width to use and what fill character to use if you want leading '0's output as you do here. Hint. look up manipulators.
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  10. #10
    Join Date
    Jul 2012
    Posts
    15

    Re: Help with recursive function

    I finally managed to resolve the situation. And here it is the final code:

    Code:
    #include <iostream>
    #include <cstdlib>
    #include <iomanip>
    
    using namespace std;
    
    void separate(int number)
    {
        // If the number is below 1000 - print it because it holds exactly or below 3 digits
        if (number < 1000)
        {
            cout << number;
        }
        else
        {
            int temp = number % 1000; // Variable which holds the remainder of the calculation (the last 3 digits of the integer)
            number = number / 1000; // Remove the last 3 digits and pass the remaining of the integer again to the function
            separate(number);
            cout << "," << setfill('0') << setw(3) << temp;
        }
    }
    
    int main()
    {
        int input;
        cout << "Enter your number :" << endl;
        cin >> input;
        separate(input);
        cout << endl;
    
        system("PAUSE");
        return 0;
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center