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:

- 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.is thrown when the data type doesn’t match.**FormatExecption** - 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. - For this reason, we first determine the total number of digits in the entered value. And run a loop.
returns a value with double data type. So it needs to be converted to integer value. The above function returns**Math.Pow(x, y)****x**.^{y}

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