how do i get my program to add the numbers in a single integer, e.g 123456, so it will do 1+2+3+4+5+6 ????

Help please

Printable View

- 04-30-2003PR1MOC++ help!!!!! Adding integers
how do i get my program to add the numbers in a single integer, e.g 123456, so it will do 1+2+3+4+5+6 ????

Help please - 04-30-2003Jamsan
I just got my pupils dialated, so I reall'y cant see your code...if you could make it a little bigger that'd be great...

- 04-30-2003ygfperson
Step 1: Divide a number into its different digits

Step 2: Add them

Example: x = 1234

x % 10 = 4

x /= 10

x % 10 = 3

etc...

you can figure out how to write a loop to do this for you - 04-30-2003DougDbug
First, convert it to a string. You can use sprintf(). I think some compilers have itoa() (integer to ascii), but I also think this is not ANSI standard.

Convert each character in the string to a single-character "string".

Use atio() (ascii to integer) to get the individual "numbers".

Add 'em up in a loop.

Or, you could do it mathmatically... using division to shift the numbers right into the one's position, etc. ( I haven't completely thought-out the algorithm) again adding them up in a loop.

[EDIT]

Look up "modulus" if you don't understand what ygfperson

is doing.