Thread: Writing program that prints out each digit of an entered number, loop question

  1. #1
    Registered User
    Join Date
    Oct 2014
    Posts
    225

    Writing program that prints out each digit of an entered number, loop question

    I'm writing a program that prints out each digit of an entered (integer) number, and stores each digit in an array. I have two functions, main and another function that does the calculations itself. The program needs to cut off ( / 10) each digit in the number and save it seperately so it can all be printed at the end, but to do that it needs to know how many digits (actual filled out digits, not just index...... I think) are in the array, which I assume requires a loop that cuts off every digit and makes another counting variable go up- but what would be the condition, since to do that the correct number of times you would need to know how many digits are in the array!
    My current code is:
    Code:
    #include <iostream>
    #include <iomanip>
    #include <cmath>
    using namespace std;
    
    
    int explode(int number, int array[])
    {
        int store = 0;
        for(int i = 0; i < array[10]; i++) {
                cin >> array[i];
                store = array[i];
                }
        
    }
    
    
    int main()
    {
    	int digits[10];
    	int numdigits;
    	
    	int n;
    	cout << "Enter number: ";
    	cin >> n;
    	
    	numdigits = explode(n,digits);
    	
    	cout << "[" << digits[0];
    	for( int i = 1; i < numdigits; i++ )
    		cout << "," << digits[i];
    	cout << "]" << endl;
    }
    If I am understanding anything wrong please tell me, I don't have a good understanding of the problem in the first place. Also I know my main function is correct, there are no problems with it. It's something in my understanding of the problem.

  2. #2
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    You should google your problems more.

    c - Getting each individual digit from a whole integer - Stack Overflow

    Code:
    int score = 123456789;
    
    while(score)
    {
        printf("%d\n", score % 10);
        score /= 10;
    }

  3. #3
    Registered User
    Join Date
    Oct 2014
    Posts
    225
    Without the printf, what variable would be the variable printed? Score I assume?

  4. #4
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Quote Originally Posted by Kelton2 View Post
    Without the printf, what variable would be the variable printed? Score I assume?
    Each digit of score.

    You should only call std::cin once this whole program, just to get the initial integer.

    You should then be able to use this while-loop to "explode" that integer and store each digit in an array. How you choose to store things is up to you but this while loop will give you the extracted digits.

    Note that this while-loop will give you digits starting from the right so the first number output from the code I posted would be 9 and the last number output will be 1.

  5. #5
    Registered User
    Join Date
    Oct 2014
    Posts
    225
    Doesn't work:
    Code:
    #include <iostream>
    #include <iomanip>
    #include <cmath>
    using namespace std;
    
    
    int explode(int number, int array[])
    {
        int score = 123456789;
     
    while(score)
    {
       // printf("%d\n", score % 10);
        score /= 10;
    }
    return score;
    }
    
    
    int main()
    {
    	int digits[10];
    	int numdigits;
    	
    	int n;
    	cout << "Enter number: ";
    	cin >> n;
    	
    	numdigits = explode(n,digits);
    	
    	cout << "[" << digits[0];
    	for( int i = 1; i < numdigits; i++ )
    		cout << "," << digits[i];
    	cout << "]" << endl;
    }

  6. #6
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    It doesn't work because you don't know what the code I posted does.

    That's funny because this works perfectly for me :
    Code:
    #include <iostream>
    #include <cassert>
    
    
    void extract
    (
    const int n,
    const int capacity,
    int *digits,
    int &num_digits
    )
    {
        int cpy = n;
    
    
        while (cpy)
        {
            assert(num_digits < capacity && "Too many digits!");
    
    
            const int digit = cpy % 10;
            cpy /= 10;
    
    
            digits[num_digits] = digit;
    
    
            ++num_digits;
        }
    }
    
    
    int main(void)
    {
        int data[64] = { 0 };
    
    
        const int n = 123456789;
    
    
        int num_digits = 0;
    
    
        extract(n, 64, data, num_digits);
    
    
        for (int i = 0; i < num_digits; ++i)
            std::cout << data[i] << std::endl;
    
    
        return 0;
    }
    And for the future, saying, "doesn't work" isn't exactly productive.

  7. #7
    Registered User Alpo's Avatar
    Join Date
    Apr 2014
    Posts
    877
    Did you try looping through with a simple number and applying the modulus and division operators? I have a feeling you are failing because you made the program too complex before you had the mechanism by which it works working correctly. Always remember to go slow and plan ahead, it saves time in the long run.

    Image the following sequence of events:

    1. We have a number: 123456789

    2. We get the remainder of dividing the number by 10 (modulus) which is: 9.

    3. We can store this number in an array if we want.

    4. We lop off the first digit by actually dividing by 10, now the number is: 12345678

    5. Goto step 1
    WndProc = (2[b] || !(2[b])) ? SufferNobly : TakeArms;

  8. #8
    Registered User
    Join Date
    Oct 2014
    Posts
    225
    Quote Originally Posted by MutantJohn View Post
    It doesn't work because you don't know what the code I posted does.

    That's funny because this works perfectly for me :
    Code:
    #include <iostream>
    #include <cassert>
    
    
    void extract
    (
    const int n,
    const int capacity,
    int *digits,
    int &num_digits
    )
    {
        int cpy = n;
    
    
        while (cpy)
        {
            assert(num_digits < capacity && "Too many digits!");
    
    
            const int digit = cpy % 10;
            cpy /= 10;
    
    
            digits[num_digits] = digit;
    
    
            ++num_digits;
        }
    }
    
    
    int main(void)
    {
        int data[64] = { 0 };
    
    
        const int n = 123456789;
    
    
        int num_digits = 0;
    
    
        extract(n, 64, data, num_digits);
    
    
        for (int i = 0; i < num_digits; ++i)
            std::cout << data[i] << std::endl;
    
    
        return 0;
    }
    And for the future, saying, "doesn't work" isn't exactly productive.
    Is there a way to do it without cassert? I don't like using header files I don't know how to use.

  9. #9
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    You don't know what assert() is?

    So... You don't know what modulo is and now you don't know what assert() is... Homie-manger, you gotta start doing some reading.

    Here's a modulus explanation : Math Forum - Ask Dr. Math

    And as for assert, assert - cppreference.com

    Google is your friend, man.

    Now, if you're curious about how I used it the way that I did, I'd be happy to tell you but you need to first off, read Alpo's post and understand it then read up on what the modulo operator does and what assert() does. These are pretty basic things that you need​ to know.

  10. #10
    Registered User
    Join Date
    Oct 2014
    Posts
    225
    Thanks, but it only almost works. It prints the numbers backwards, and with an extra , that IDK how to easily get rid of.
    Code:
    Code:
    #include <iostream>
    #include <cassert>
    using namespace std; 
    void extract
    (
    const int n,
    const int capacity,
    int *digits,
    int &num_digits
    )
    {
        int cpy = n;
     
     
        while (cpy)
        {
            assert(num_digits < capacity && "Too many digits!");
     
     
            const int digit = cpy % 10;
            cpy /= 10;
     
     
            digits[num_digits] = digit;
     
     
            ++num_digits;
        }
    }
     
     
    int main()
    {
        int data[64] = { 0 };
        int n2;
        cin >> n2;
        const int n = n2;
        int num_digits = 0;
        extract(n, 64, data, num_digits);
        cout << "[";
        for (int i = 0; i < num_digits; ++i) {
            cout << data[i] << ",";
    }
    cout << "]";
     
        return 0;
    }

  11. #11
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    It doesn't print the numbers backwards.

    I told you in my earlier posts that it reads right to left so 9 is the first digit.

    This makes sense as 123456789 is really the sum of 9 * 10^0 + 8 * 10^1 + 7 * 10^2 + ...

    The array is stored such that the index of the element is also the proper power. This is why 9 is at 0, 8 is at 1, 7 is at 2, etc.

    This means you need to print your array in reverse so you start at num_digits - 1 and go all the way to 0.

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Kelton2
    it only almost works. It prints the numbers backwards
    Ah, and that is the crux of this exercise: if you "extract" the digits using modulo 10 in a loop and print them at the same time, you will end up printing the digits in reverse. There are two common solutions to this problem:
    • Use an explicit stack. For example, you could store each digit extracted in an array starting from index 0, then loop over the array in reverse to print.
    • Use recursion instead of iteration. Basically, you extract the digit in the one's place, and if the number is greater than 9, recursively call the function to print the rest of the digits (i.e., by dividing the number by 10, with truncation, then passing it as the argument to the recursive call), then print the current digit. This way pretty much makes use of an implicit stack.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Oct 2014
    Posts
    225
    Quote Originally Posted by MutantJohn View Post
    It doesn't print the numbers backwards.

    I told you in my earlier posts that it reads right to left so 9 is the first digit.

    This makes sense as 123456789 is really the sum of 9 * 10^0 + 8 * 10^1 + 7 * 10^2 + ...

    The array is stored such that the index of the element is also the proper power. This is why 9 is at 0, 8 is at 1, 7 is at 2, etc.

    This means you need to print your array in reverse so you start at num_digits - 1 and go all the way to 0.
    I'm still confused? What array/variable do I need to change to what to make it print right?

  14. #14
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Quote Originally Posted by Kelton2 View Post
    I'm still confused? What array/variable do I need to change to what to make it print right?
    I've basically already done your homework for you. Surely, you can figure this out on your own. If you don't know what array is storing the digits in the code I posted, I don't know what to tell you other than, re-read the code but this time, for understanding.

  15. #15
    Lurker
    Join Date
    Dec 2004
    Posts
    296
    Quote Originally Posted by MutantJohn View Post
    I've basically already done your homework for you. Surely, you can figure this out on your own. If you don't know what array is storing the digits in the code I posted, I don't know what to tell you other than, re-read the code but this time, for understanding.
    I'm not so sure the OP can figure this out.

    He clearly doesn't understand the problem at all or how to solve it. You gave him a link with a solution, but I don't think he even understands the basic math involved to solve this with pen and paper.

    My suggestion to the OP is to take a step back and make sure that you understand the math/problem behind the solution.
    "A Professor of Computer Science gave a paper on how he uses Linux to teach his undergraduates about operating systems. Someone in the audience asked why use Linux rather than Plan 9?' and the professor answered:Plan 9 looks like it was written by experts; Linux looks like something my students could aspire to write'."

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 14
    Last Post: 01-09-2013, 06:35 AM
  2. Replies: 8
    Last Post: 12-30-2010, 10:08 PM
  3. Replies: 10
    Last Post: 09-24-2010, 01:09 AM
  4. Replies: 2
    Last Post: 10-31-2009, 06:49 PM
  5. Replies: 7
    Last Post: 05-26-2003, 05:44 PM