w3resource

C#: Compute the sum of the digits of an integer


Sum of Digits in Integer

Write a C# program and compute the sum of an integer's digits.

C# Sharp Exercises: Compute the sum of the digits of an integer

Sample Solution:-

C# Sharp Code:

using System;

// This is the beginning of the Exercise27 class
public class Exercise27 {
    // This is the main method where the program execution starts
    public static void Main() {
        Console.Write("Input a number(integer): "); // Prompting user for input

        int n = Convert.ToInt32(Console.ReadLine()); // Reading user input as an integer

        int sum = 0; // Initializing a variable to store the sum of digits

        // Loop to calculate the sum of digits
        while (n != 0) {
            sum += n % 10; // Adding the last digit of 'n' to the 'sum' variable
            n /= 10; // Removing the last digit from 'n'
        }

        // Displaying the sum of the digits of the input number
        Console.WriteLine("Sum of the digits of the said integer: " + sum);
    }
}

Sample Output:

Input  a number(integer): 12                                           
Sum of the digits of the said integer: 3

Flowchart:

Flowchart: C# Sharp Exercises - Compute the sum of the digits of an integer

For more Practice: Solve these Related Problems:

  • Write a C# program to compute the sum of digits of an integer and count how many of them are even.
  • Write a C# program to recursively sum all the digits of a number until a single digit remains.
  • Write a C# program to find the difference between the sum of even-position digits and the sum of odd-position digits of an integer.
  • Write a C# program to reverse an integer and compute the sum of both original and reversed numbers’ digits.

Go to:


PREV : Sum of First 500 Primes.
NEXT : Reverse Words in Sentence.

C# Sharp Code Editor:



What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.