Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C- How to add digits in a number?

How do I add the digits in a particular number for example if the number is 3234 the result should be 3+2+3+4 = 12?

like image 381
nishantcm Avatar asked Dec 12 '22 18:12

nishantcm


1 Answers

Something along the lines of this should do it:

int val = 3234;

int sum = 0;
while (val != 0) {
    sum += (val % 10);
    val = val / 10;
}

// Now use sum.

For continued adding until you get a single digit:

int val = 3234;

int sum = val;
while (sum > 9) {
    val = sum;
    sum = 0;
    while (val != 0) {
        sum += (val % 10);
        val = val / 10;
    }
}

// Now use sum.

Note that both of these are destructive to the original val value. If you want to preserve it, you should make a copy or do this in a function so the original is kept.

like image 187
paxdiablo Avatar answered Jan 11 '23 14:01

paxdiablo