Write a C# program to find the sum of digits

How to find the sum of digit in C#. In the below example another way to find the some of digit in C#. In this post we will see how to calculate sum of the digits in a C# program.

Algorithm for sum of digits in a given number:

  1. Take input of the number
  2. Declare a variable as sum name, to store the sum and set it to 0
  3. Declare a while loop and give a condition to repeat the next two steps untill we get the number is 0
  4. Now getting the rightmost digit of the number with the help of remainder ‘%’ operator by taking its mode by 10 and add it to sum.
  5. Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.
  6. At the end print or return the sum which is the result.
Input sample:

123

Output we get:

6

In above example we can see clearly that it is Calculating the sum of the digits by 1+2+3= 6

Sum of Digits Program Examples in C#

There are many ways to find the sum of digits by different techniques some of them are as follows-

Iterative method

With this method we make the loop for calculating sum of any given digits by taking the digit in a variable and one by one adding the digits and storing in other variable each time. The number we have for taking its digits one by one we put it in the while loop condition till it’s greater to 0.

using System;
namespace CSharpProgram
{
class Program
public static void Main(string[] args)

{

int num,sum=0;

Console.Write("Enter a number to find the sum of digits: ");

num = int.Parse(Console.ReadLine());

while (num > 0)

{

sum = sum + num % 10;

num = num / 10;

}

Console.Write("Total sum= " + sum);

    }

  }

}
Input:

Enter a number to find the sum of digits: 172

Output:

Total sum= 10

Computing in a single line

This function has three lines instead of one line, but it calculates the sum in a line. It can be made one-line function if we pass the pointer to sum.

using System; 
namespace CSharpProgram 
{ 

class Program 
{

public static void Main(string[] args) 

{ 

int num,sum=0;

Console.Write("Enter a number to find the sum of digits: "); 

num = int.Parse(Console.ReadLine());

int sum,num;

/* Single line that calculates sum */

for (sum = 0; num > 0; sum += num % 10, num /= 10);


    }

   Console.Write("Total sum= " + sum);

  }

}
Input:

Enter a number to find the sum of digits: 45

Output:

Total sum= 9

So with the help of these programs you can find the sum of the digits in C#. I hope you have like this post and you can also check some more program of C# with below links.

More C# program with example

Find Fibonacci series in C# 

Check prime number in C#