# Array

• 03-07-2010, 01:45 PM
Cutie
Array
how to solve this question?

Question: Write a function that takes as parameter an integer value and returns the sum of the digits in the integer, e.g. if the integer is 4123, then the function returns value 10(i.e. 4+1+2+3).Note that the integer can contain any number of digits.
• 03-07-2010, 02:05 PM
JosAH
Quote:

Originally Posted by Cutie
how to solve this question?

Question: Write a function that takes as parameter an integer value and returns the sum of the digits in the integer, e.g. if the integer is 4123, then the function returns value 10(i.e. 4+1+2+3).Note that the integer can contain any number of digits.

This can easily be solved using a little recursive method; a few simple observations:

1) let S(n) be the function we're looking for.
2) the sum of the digits in the number zero (0) equals 0, i.e. S(0) == 0
2) let a number be written as the digits d_1 d_2 ... d_n then the sum of all the digits equals S(d_1 d_2 ... d_n-1)+d_n

Observations 2) and 3) lead to the following function:

Code:

```int S(int n) {   if (n == 0) return 0; // observation 2)   return S(n/10)+n%10; // observation 3) }```
As you can see no array is needed at all.

kind regards,

Jos