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?
Asked
Active
Viewed 2,682 times
4
-
not an iPhone or objective-c problem... just algorithm – Benoît Oct 27 '10 at 11:33
2 Answers
12
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.

paxdiablo
- 854,327
- 234
- 1,573
- 1,953
-
-
thanks! now if I want to iterate this process until I get a single digit no from 1 to 9 how to do it. – nishantcm Oct 27 '10 at 12:30
-
-
while (len > 1) { sum=0; while (val != 0 ) { sum += (val % 10); val = val / 10; } val=sum; temp=[NSString stringWithFormat:@"%d", sum ]; len=[temp length]; } – nishantcm Oct 27 '10 at 12:51
-
Thanks! I could have done this thing so easily instead of finding the length and writing all that code to convert int to string. – nishantcm Oct 28 '10 at 09:07
2
Hope it is not your homework !
int sum = 0;
while (value!=0) {
sum += value % 10;
value = value / 10;
}

Benoît
- 7,395
- 2
- 25
- 30
-
actually i have an idea about how to do this in php, but am unable to do this in objective c. – nishantcm Oct 27 '10 at 12:29
-
actually my algo in php sort of treats the number as an array. like number[0], number[1] and uses for each to add all the digits. – nishantcm Oct 27 '10 at 12:51