C# Program to find the sum of digits of a number


In this program, You will learn how to find the sum of digits of a number in C#.


201 = 2 + 0 + 1 => 3

193 = 1 + 9 + 3 => 13

Example: How to find the sum of digits of a number in C#.

using System;
public class Program
{
	public static void Main(string[] args)
	{
		int n, r, s = 0;
		Console.Write("Enter a number:");
		n = Convert.ToInt32(Console.ReadLine());

		while (n > 0)
		{
			r = n % 10;
			s = s + r;
			n = n / 10;
		}
		Console.WriteLine("Sum of digits:" + s);
	}
}

Output:

Enter a number:234
Sum of digits:9