Sum of Digits
Program in C#
static void
SumOfNumbers() {
Console.Write("Enter the Number : "); int
number = int.Parse(Console.ReadLine()); int sum =
0, reminder; while
(number > 0) {
reminder = number % 10;
sum = sum + reminder;
number = number / 10; }
Console.WriteLine($"The Sum of Digits is : {sum}"); } |
Using Linq to
find the sum of digits of a number in C#:
static void
SumOfNumbers() {
Console.Write("Enter the Number : "); int
number = int.Parse(Console.ReadLine()); int sum =
number.ToString().Select(digit => int.Parse(digit.ToString())).ToArray().Sum();
Console.WriteLine($"The Sum of Digits is : {sum}");
Console.ReadKey(); } |
EmoticonEmoticon