0

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

4
Contributors
6
Replies
7
Views
7 Years
Discussion Span
Last Post by Ryan61343
0

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

0

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

0

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

Edited by tesuji: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.