Sum of Digits Program in C#
Posted by Superadmin on August 10 2022 14:31:06

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.

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