Alex
Alex

Reputation: 55

C# recursive method

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));
         }
 }

Upvotes: 1

Views: 134

Answers (4)

Huseyin Durmus
Huseyin Durmus

Reputation: 440

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));
        }
    }

Upvotes: 0

Aimnox
Aimnox

Reputation: 899

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.

Upvotes: 0

Ranjit Singh
Ranjit Singh

Reputation: 3735

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);
     }
}

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 157136

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)

Upvotes: 5

Related Questions