1

right now I am trying to practice recursion, but I got stuck. The objective is to to sum up all the digits of the number. For example method's signature takes one int parameter. This parameter is number (for example 123). And recursively i should sum up 1+2+3 , and give an answer of 6.

So far I tried :

(It probably does not make sense, but I tried a lot)

 public int sumofD(int n)
 {
         if (n == 0)
         { return 0; }
         else
         {
               return  n % 10 + sumofD(n-(n%10));
         }
 }
1
  • You should accept one answer Commented May 23, 2016 at 8:58

4 Answers 4

5

sumofD(n-(n%10)) makes 10 from n = 11 (11-(11%10) = 11-1 = 10). That will cause your recursive method to never end. You are not actually dividing anything, so the loop is endless.

Simply dividing with 10 will do the job here:

sumofD(n / 10)
Sign up to request clarification or add additional context in comments.

Comments

1

You are doing it wrong, n - (n%10) will make 123 to 123-3, i.e 120

public int sumofD(int n)
{
     if (n == 0)
     { return 0; }
     else
     {
           return  n % 10 + sumofD(n/10);
     }
}

2 Comments

And this is why just providing a fix to the code is a good, but not great, answer. You forgot to explain what they did wrong.
Thanks, if someone will give me time to edit my answer then only I will :)
0

For what I understand you also need to sum the result if it's more than one digit.

So 99 will give you 9 (9+9=18, 8+1=9)

Then another way of doing it will be:

public int sumofD(int n)
{
    string str = n.ToString();
    int total = 0;
    foreach (char c in str.ToCharArray())
    {
        total += int.Parse(c+"");
    }
    if (total > 9) total = sumofD(total);
    return total;
}

If you just need the direct sum (99 give you 18) you can just delete the last if line.

Comments

0

I rewrote function (sum of). I tried it is working

    public int sumofD(int n)
    {
        if (n == 0)
        { return 0; }
        else
        {
            return (n % 10 + sumofD(n / 10));
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.