Sum of digits in C Sharp

Sum of digits

We are using a loop and mathematical operations to print the sum of digits in C#.

Algorithm:

  • Step 1: Take input from the user.
  • Step 2: The modulus/remainder of the number is then calculated.
  • Step 3: The remainder of the number is then summed.
  • Step 4: The number is then divided by 10.
  • Step 5: Step 2 is repeated while the number is greater than 0.

Example:

using System;  
  public class Example  
   {  
     public static void Main(string[] args)  
      {  
       int num, sum=0, x;         
       Console.Write("Enter a number: ");      
       num = int.Parse(Console.ReadLine());     
       while(num>0)      
       {      
        x = num%10;      
        sum = sum + x;      
        num = num/10;      
       }      
       Console.Write("Sum of digits= " + sum);       
     }  
  }

Output:

Explanation:

In the above example, we are printing the sum of the digits in C#.