what would be a good way to go about summing the digits of an int for example say i put in 3456 the sum of thos would be 18 but i have no idea how to get the numbers to sum from a single integer

Recommended Answers

All 6 Replies

I would use std::stringstream to put the int into a stirng. Then the logic is much more straight forward to get each digit of the string. You can again use stringstream to get each one back to an int before adding them.

iamthewee's option also works, but it could be more confusing to read in my opinion.

Dave

i know how to do it iteratively using the % operator but what im trying to do is do it recursively

Hi Ryan

Try this snippet:

int splitsum= 0; 
void splitadd(unsigned int n){
  int d = n % 10; n = n / 10; if ( n > 0) splitadd (n); splitsum += d;}

... 

// in main() add this: 
splitadd(12345); cout << "Result: " << splitsum << endl;  // Result: 15

-- tesu

whatabout to keep doing it till you reach one digit

i would prefer just ideas not actual code though

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.