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);
Console.Read();
}
}
}
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).