Sum of Digits Program in C#

This is a C# Program to get a number and display the sum of the digits.

Problem Description

This C# Program Gets a Number and Display the Sum of the Digits.

Problem Solution

The digit sum of a given integer is the sum of all its digits.

Program/Source Code

Here is source code of the C# Program to Get a Number and Display the Sum of the Digits. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Get a Number and Display the Sum of the Digits 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, sum = 0, r;
            Console.WriteLine("Enter a Number : ");
            num = int.Parse(Console.ReadLine());
            while (num != 0)
            {
                r = num % 10;
                num = num / 10;
                sum = sum + r;
            }
            Console.WriteLine("Sum of Digits of the Number : "+sum);
            Console.ReadLine();
 
        }
    }
}
Program Explanation

In this C# program, we are reading a number using ‘num’ variable. Using while loop computes the sum of the digits. The digit sum of a given integer is the sum of all its digits.
Compute the modulus of the value of ‘num’ variable by 10. Divide the value of ‘num’ variable by 10. Compute the summation of the value of ‘sum’ variable with the value of ‘r’ variable. Print the sum of the digits.

advertisement
advertisement
Runtime Test Cases
 
Enter a Number : 123
Sum of Digits of the Number : 6

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.