# C# program to find sum of all digits of a given number

Learn: How to find sum of all digits of a given number using C# program, this post has solved program with explanation.
Submitted by Ridhima Agarwal, on September 17, 2017

Given an integer number and we have to find sum of all digits.

Example:

```Input: 567
Output: 18
```

The logic, we are using here - is that, first of all we will extract the digits one by one using modulus (%) operator and then will add those digits in a temporary variable named sum, this process will be executed until the value of number is not 0.

Consider the program:

```using System;

namespace system
{
class sumofdigits
{
static void Main(String[] args)
{

int a=567, sum=0, b;

//condition to check if the number is not 0
while(a!=0)
{
b=a%10;       //extract a digit
a=a/10;      //remained number
}
Console.WriteLine("The sum of the digits is: " +sum);
}
}
}
```

Output

```The sum of the digits is: 18
```

Explanation:

```Inital value of a (input number): a = 567

Iteration 1:
b = a%10 → 567%10 = 7
sum = sum+b → 0+7 = 7
a = a/10 → 567/10 = 56

Iteration 2:
b = a%10 → 56%10 = 6
sum = sum+b → 7+6 = 13
a = a/10 → 56/10= 5

Iteration 3:
b = a%10 → 5%10 = 5
sum = sum+b → 13+5= 18
a = a/10 → 5/10 = 0

Now, the value of a is "0", condition will be fasle
Output will be 18.

```

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates