# Sum of Digits Program in C#

«
»

This is a C# Program to get a number and display the sum of the digits.

Problem Description

This C# Program Gets a Number and Display the Sum of the Digits.

Problem Solution

The digit sum of a given integer is the sum of all its digits.

Program/Source Code

Here is source code of the C# Program to Get a Number and Display the Sum of the Digits. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

```/*
* C# Program to Get a Number and Display the Sum of the Digits
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Program
{
class Program
{
static void Main(string[] args)
{
int num, sum = 0, r;
Console.WriteLine("Enter a Number : ");
while (num != 0)
{
r = num % 10;
num = num / 10;
sum = sum + r;
}
Console.WriteLine("Sum of Digits of the Number : "+sum);

}
}
}```
Program Explanation

In this C# program, we are reading a number using ‘num’ variable. Using while loop computes the sum of the digits. The digit sum of a given integer is the sum of all its digits.
Compute the modulus of the value of ‘num’ variable by 10. Divide the value of ‘num’ variable by 10. Compute the summation of the value of ‘sum’ variable with the value of ‘r’ variable. Print the sum of the digits.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Runtime Test Cases
```
Enter a Number : 123
Sum of Digits of the Number : 6```

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.