C++ Programming Exercises?

Follow
  • Follow publicly
  • Follow privately
  • Unfollow
1. Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the ...show more
Update : What would I have to do to a string to make the digits print out ...show more
Update 2: Okay that works, but how do I get the numbers to output forwards instead ...show more
Best AnswerAsker's Choice
Hi dude,

Your while loop will never gets end because n variable will always remains greater than zero until it overflows.

Replace your while loop with the following one:

// store number in a temporary variable,
// or you can use number variable directly.
int temp = number;
// for negative numbers:
if (temp < 0) temp *=-1;

while (temp)
{
cout << (temp % 10) << " ";
temp /= 10;
}

======================================
// First calculate number of digits:
int digitsNum = 0;
int temp = number;
if (temp < 0) temp *=-1;
for (; temp; temp/=10, digitsNum++);

// after that...
int *list = new int[digitsNum];
temp = number;
if (temp < 0) temp *=-1;

// Store digits in the list
for (int i=0; temp; i++, temp /= 10)
*(list + i) = (temp % 10);

// At last, print it at reverse side
for (int i=digitsNum - 1; i >= 0; i--)
cout << list[i] << " ";

good luck...

Source:

My knowledge and experience

Asker's rating & comment

5 out of 5
Thanks!
  • Rate
  • Comment

Other Answers (1)

  • The Phlebob answered 5 years ago
    Your code could be much simpler if you input the number as a string and manipulated the characters rather than dealt with an int. For one thing, you wouldn't have a problem with numbers that exceed the range of an int (often -32767 to +32768 or so).

    As a footnote to that, since you do have to do some numerical manipulation, note that any ASCII digit can be converted to its integer value simply by subtracting the character '0' from it.

    Hope that helps.
    • Rate
    • Comment
  • Sign In 

    to add your answer

Who is following this question?

    %
    BEST ANSWERS
    Member Since:
    Points: Points: Level
    Total Answers:
    Points this week:
    Follow
     
    Unfollow
     
    Block
     
    Unblock