Exclusive Clothing Sale On Soft & Soothe

Get up to 63% off on our latest collection.

Shop Now

Sum of Digits Program in C#

 

Sum of Digits Program in C#


In this Article we will see the sum of number , for ex.
 if number is 123 then sum of number is 1+2+3 = 6

        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}");

        }


Output







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();

        }


Share this

Related Posts

Previous
Next Post »

Exclusive Clothing Sale On Soft & Soothe

Get up to 63% off on our latest collection.

Shop Now