Start with the summation, because that's easy. You already seem to know about taking the remainder of ten to get the least significant digit and dividing by ten to slice it off. Remember to keep it as simple as possible. When you do this with more than one loop, you're not keeping it simple:
#include <iostream>
int main()
{
std::cout<<"Enter a number: ";
int num;
if ( std::cin>> num ) {
int sum = 0;
if ( num < 0 )
num = -num;
while ( num != 0 ) {
sum += num % 10;
num /= 10;
}
std::cout<<"The sum is "<< sum <<'\n';
}
}
The fun part is getting the digits to print out from most significant to least significant, as per your example using 3456. If you just print
num % 10 in the while loop, you can get the digits in reverse. To print in the right order, you need to store the digits somewhere (the simpler solution, IMO), or extract the digits from most significant to least significant.
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Offline 11,807 posts
since Sep 2004