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.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Since we're now giving out alternative solutions, here's mine:
#include <iostream>
#include <iterator>
template <typename OutIt>
int sum_digits ( int value, int radix, OutIt *it = 0 )
{
if ( value == 0 )
return 0;
int digit = value % radix;
int sum = sum_digits ( value / radix, radix, it ) + digit;
if ( it != 0 )
*it++ = digit;
return sum;
}
int main()
{
std::cout<<"Enter an integer: ";
int value;
if ( std::cin>> value ) {
int sum = sum_digits ( value, 10,
&std::ostream_iterator<int> ( std::cout, " " ) );
std::cout<<"\nThe sum is "<< sum <<'\n';
}
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
and another one :
#include <iostream>
#include <string>
#include <algorithm>
#include <numeric>
#include <iterator>
using namespace std;
int main(){
string num;
cin >> num;
//print each digit
std::copy( num.begin(), num.end(), std::ostream_iterator<char>(cout," "));
//get sum
int sum = std::accumulate(num.begin(),num.end(),0) - '0' * num.size();
cout << "sum is = " << sum << endl;
return 0;
}
Yes I know, no error checking. Thats because the user knows better, than to mess with me or my program.
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608