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);
of number:{0}", sum);
}
int getSumFromRecursion(int num) {
if (num == 0)
return 0;
return (num % 10
+ getSumFromRecursion(num / 10));
+ getSumFromRecursion(num / 10));
}
[TestMethod]
public void TestSumOfDigitUsingRecursion()
{
BasicProgramming basicProgramming
= new BasicProgramming();
= new BasicProgramming();
string output = basicProgramming
.SumOfDigitWithRecursion(123);
.SumOfDigitWithRecursion(123);
Assert.AreEqual("Sum of digits of
number:6", output);
number:6", output);
}
How to find sum of digit using recursion
using dry run method
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
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 | public string SumOfDigitWithRecursion(int num) |
Comments
Post a Comment