C++ help!!!!! Adding integers

This is a discussion on C++ help!!!!! Adding integers within the C++ Programming forums, part of the General Programming Boards category; how do i get my program to add the numbers in a single integer, e.g 123456, so it will do ...

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    2

    C++ 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

  2. #2
    Registered User
    Join Date
    Feb 2003
    Posts
    162
    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...

  3. #3
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,493
    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

  4. #4
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    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.
    Last edited by DougDbug; 04-30-2003 at 06:48 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about adding integers to char
    By blueshift1980 in forum C++ Programming
    Replies: 6
    Last Post: 04-16-2009, 01:51 PM
  2. SVN Import Causes Crash
    By Tonto in forum Tech Board
    Replies: 6
    Last Post: 11-01-2006, 03:44 PM
  3. adding 16bit and 32 bit integers
    By kris_perry2k in forum C Programming
    Replies: 2
    Last Post: 12-08-2005, 09:49 AM
  4. Adding integers to a string
    By Kyoto Oshiro in forum C++ Programming
    Replies: 3
    Last Post: 02-23-2004, 08:01 AM
  5. Adding arrays of integers in a node struct
    By emilyashu in forum C Programming
    Replies: 7
    Last Post: 04-26-2003, 07:19 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21