Calculating the Sum of Digits of an Integer in C#: A Simple and Efficient Algorithm

Learn how to calculate the sum of the digits of an integer in C#. This tutorial provides a clear and concise code example using a `while` loop and basic arithmetic operations, demonstrating a fundamental algorithm for digit manipulation.



Calculating the Sum of Digits in C#

Introduction

This article demonstrates a simple C# program to calculate the sum of the digits of an integer entered by the user. We'll use a loop and basic mathematical operations to achieve this.

Algorithm for Summing Digits

  1. Get the number as input from the user.
  2. Find the remainder when the number is divided by 10 (this gives the last digit).
  3. Add the remainder to a running sum.
  4. Divide the number by 10 (integer division removes the last digit).
  5. Repeat steps 2-4 until the number becomes 0 (all digits have been processed).

C# Code Implementation

C# Code for Summing Digits

using System;

public class SumExample {
    public static void Main(string[] args) {
        int n, sum = 0, m;
        Console.Write("Enter a number: ");
        n = int.Parse(Console.ReadLine());
        while (n > 0) {
            m = n % 10;
            sum = sum + m;
            n = n / 10;
        }
        Console.Write("Sum is= " + sum);
    }
}
Example Output

Enter a number: 23
Sum is= 5

Enter a number: 624
Sum is= 12
        

Explanation

The code takes an integer as input. The `while` loop repeatedly extracts the last digit using the modulo operator (`%`), adds it to the sum, and then removes the last digit using integer division (`/`). The loop continues until all digits are processed.

Conclusion

This program provides a straightforward method for calculating the sum of digits using a basic algorithm and C#'s built-in arithmetic operators. This technique is easily adaptable to various number systems or data types.