Home / Programs / Sum of digits program in C#
🚀 Programming Example

Sum of digits program in C#

👁 310 Views
💻 Practical Program
📘 Step Learning

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#.

💻 Program Code

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

🖥 Program Output

Output 1:
Enter a number: 23  
Sum is= 5

Output 2:
Enter a number: 624       
Sum is= 12
                            

📘 Explanation

None
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.