Sum of digits program in C#

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Sum of digits program in C#

We can write the sum of digits program in C# language by the help of loop and mathematical operation only.

Sum of digits algorithm

To get sum of each digit by C# program, use the following algorithm:

  • Step 1: Get number by user
  • Step 2: Get the modulus/remainder of the number
  • Step 3: sum the remainder of the number
  • Step 4: Divide the number by 10
  • Step 5: Repeat the step 2 while number is greater than 0.

Let's see the sum of digits program in C#.

 
  1. using System;  
  2.   public class SumExample  
  3.    {  
  4.      public static void Main(string[] args)  
  5.       {  
  6.        int  n,sum=0,m;         
  7.        Console.Write("Enter a number: ");      
  8.        n= int.Parse(Console.ReadLine());     
  9.        while(n>0)      
  10.        {      
  11.         m=n%10;      
  12.         sum=sum+m;      
  13.         n=n/10;      
  14.        }      
  15.        Console.Write("Sum is= "+sum);       
  16.      }  
  17.   }  

Output:

Enter a number: 23  
Sum is= 5
Enter a number: 624       
Sum is= 12