Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

c arrays

  • 22-05-2007 05:27PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 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, Registered Users 2 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