Write a program to print the sum of all digits in a number using c#

Below is the code to find the sum of all the digits in a number.

using System;
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
try
{
int input = int.Parse(Console.ReadLine());
int length = input.ToString().Length;
int sum = 0;
int power = length-1;
for (int i = 0; i < length; i++)
{
int denominator = Convert.ToInt32(Math.Pow(10, power));
sum = sum + (input / denominator);
input = input % denominator;
power = power - 1;
}
Console.WriteLine("sum of the digits: {0}", sum);
}
catch (FormatException e)
{
Console.Write(e.Message);
}
Console.ReadKey();
}
}

Notes:

  1. Number is entered in the command prompt by the end user. Try-Catch block is implemented so that if there is any issue in the input value the control is passed to the catch block and exception is thrown. FormatExecption is thrown when the data type doesn’t match.
  2. In this method, we add the digits from the left to right. For example if the number is 1234, the algorithm implemented here is in such a way that 1 is added to 2 and the sum is added to 3 and so on.
  3. For this reason, we first determine the total number of digits in the entered value. And run a loop.
  4. Math.Pow(x, y) returns a value with double data type. So it needs to be converted to integer value. The above function returns xy.

The link here will have some other ways to write the same program. In those methods the addition is done from right to left.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s