2 - Sum of digit recursion in c sharp

Sum of digit recursion in c#



 public string SumOfDigitWithRecursion(int num)
       {
           int sum = 0, r;
           sum = getSumFromRecursion(num);
           return string.Format("Sum of digits
of number:{0}", sum);
       }
       int getSumFromRecursion(int num) {
           if (num == 0)
               return 0;
           return (num % 10
+ getSumFromRecursion(num / 10));
       }
   [TestMethod]
       public void TestSumOfDigitUsingRecursion()
       {
           BasicProgramming basicProgramming
= new BasicProgramming();
           string output = basicProgramming
.SumOfDigitWithRecursion(123);
           Assert.AreEqual("Sum of digits of
number:6", output);
       }
How to find sum of digit using recursion
using dry run method
Step by step process for better understanding
of how the algorithm works.
Let number be 12345.
Step 1-> 12345 % 10 which is equal-too 5 +
( send 12345/10 to next step )

Step 2-> 1234 % 10 which is equal-too 4 +
( send 1234/10 to next step )

Step 3-> 123 % 10 which is equal-too 3 +
( send 123/10 to next step )

Step 4-> 12 % 10 which is equal-too 2 +
( send 12/10 to next step )

Step 5-> 1 % 10 which is equal-too 1 +
( send 1/10 to next step )

Step 6-> 0 algorithm stops

following diagram will illustrate the process of recursion



 1
2
3
4
5
6
7
8
9
10
11
  public string SumOfDigitWithRecursion(int num)
{
int sum = 0, r;
sum = getSumFromRecursion(num);
return string.Format("Sum of digits of number:{0}", sum);
}
int getSumFromRecursion(int num) {
if (num == 0)
return 0;
return (num % 10 + getSumFromRecursion(num / 10));
}

Comments

Popular posts from this blog

4 - Perfect number in c sharp