Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

c arrays

Options
  • 22-05-2007 5:27pm
    #1
    Registered Users Posts: 5,111 ✭✭✭


    I'm pretty new at this lark so beg your pardon if this is a simple question, I just can't figure out what to google for a procedure.

    I want to add the digits of a variable ie.

    1234 is the variable so; 1+2+3+4=10

    I assume an array is the best way to approach this am I completely on the wrong track? Any tips or quick links suggestions would be most welcome.


Comments

  • Registered Users Posts: 1,481 ✭✭✭satchmo


    Well you could either..
    (a) Convert the number to a string - aka an array of chars (there are lib functions to do this) - and then just convert each character to a number and sum, or
    (b) Observe that for an integer x, the digit at place n is (x/(10^n))%10, where n=0 denotes the least significant digit. Loop over the digits and sum the result.

    The first solution is pretty hacky - you shouldn't have to use strings to work out numeric stuff like this - but it also doesn't limit the length of the number to the size of the datatype used to store it, which the second method does.


  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    Obviously you mean the variable value you want to add as you can't have variable names starting with numbers in C.

    You could keep getting toe modulo 10 of the number.
    sum = 0
    num = 1234
    
    while (num >= 0)
    do
    [b]num % 10[/b] // = 4 - add this integer value to sum.
    [b]num = num / 10[/b] // = 123 - set this integer value to num
    endwhile
    

    if you trouble codeing this puedocode let me know.

    Think that should work.

    Edit - just noticed probably similer to satchmo 2nd method.


Advertisement