1 - Sum of digit in c sharp

Sum of digit in c#


 public string SumOfDigit(int num) {
  int sum = 0, r;
  while (num > 0)
   {
               r = num % 10;
               num = num / 10;
               sum = sum + r;
     }
           return string.Format("Sum of digits
of number:{0}", sum);
       }

       [TestMethod]
       public void TestSumOfDigit()
       {
       BasicProgramming basicProgramming
= new BasicProgramming();
        string output
= basicProgramming.SumOfDigit(123);
       Assert.AreEqual("Sum of digits of number:6"
, output);
       }

How to find sum digit using dry run method.
For example, if the input is 98, the variable sum is 0 initially
98%10 = 8 (% is modulus operator which gives us
remainder when 98 is divided by 10).

sum = sum + remainder
so sum = 8 now.

98/10 = 9 because in C language whenever we divide
an integer by an another integer we get an integer.
9%10 = 9

sum = 8 (previous value) + 9
sum = 17
9/10 = 0.

So finally n = 0, the loop ends we get the required sum.
 1
2
3
4
5
6
7
8
9
10
  public string SumOfDigit(int num) {
int sum = 0, r;
while (num > 0)
{
r = num % 10;
num = num / 10;
sum = sum + r;
}
return string.Format("Sum of digits of number:{0}", sum);
}

Comments

Popular posts from this blog

4 - Perfect number in c sharp