Write a program in C#.Net to create a function to calculate the sum of the individual digits of a given number.

Answer:

using System;

namespace Sum
{
    class Program
    {
        // Function to calculate the sum of the digits of a number
        static int SumOfDigits(int num)
        {
            int sum = 0;
            // Loop to extract each digit and add it to the sum
            while (num > 0)
            {
                sum += num % 10;  // Add the last digit to the sum
                num /= 10;  // Remove the last digit from the number
            }

            return sum;
        }

        static void Main(string[] args)
        {
            int num;

            // Taking input from the user
            Console.WriteLine("Enter a number: ");
            num = Convert.ToInt32(Console.ReadLine());

            // Calculating the sum of digits
            int result = SumOfDigits(num);

            // Displaying the result
            Console.WriteLine("The sum of the digits of given number is: " + result);
            Console.ReadLine();
        }
    }
}
Scroll to Top