Hello Learner
Contributor
Stats
 Views : 10582 Comments : 0 Rating : 0
Actions

# Sum of digits of a number in .NET using for loop

By Ashok Nalam on 17 Jul 2013 | Category: C# | Tagged: .NET number
In this program we will see how to sum the digits of a given number using for loop.
 Rate this resource

In this program we will see how to sum the digits of a given number using for loop

E.g: If user enters number as 123456 then the output will be 1+2+3+4+5+6=21

#### Program:

```namespace DotNetMirror
{
class SumofDigitsUsingForLoop
{
public static void Main()
{
int sum = 0;
Console.WriteLine(" /********** Program to sum of digits using for loop ************/");
Console.Write("Enter a number:");
int number = int.Parse(Console.ReadLine()); int tempNumber = number ;
for (; number != 0; number = number / 10)
{
sum += (number % 10);
}
Console.Write("Sum of {0} digit is {1}", tempNumber, sum);
}
}
}   ```

#### Output:

/********** Program to sum of digits using for loop ************/
Enter a number:123456
Sum of 12346 digit is 21

Note: If you want to give number beyond the int range, change the  data type of input value (number).

 Rate this resource