C# - Find the Sum of Digits of a Number

Learn: How to find sum of all digits of a given number using C# program, this post has solved program with explanation.
Submitted by Ridhima Agarwal, on September 17, 2017 [Last updated : March 19, 2023]

Given an integer number and we have to find sum of all digits.

Example

Input: 567
Output: 18

Logic

The logic, we are using here - is that, first of all we will extract the digits one by one using modulus (%) operator and then will add those digits in a temporary variable named sum, this process will be executed until the value of number is not 0.

C# program to find sum of all digits of a given number

using System;

namespace system {
  class sumofdigits {
    static void Main(String[] args) {

      int a = 567, sum = 0, b;

      //condition to check if the number is not 0
      while (a != 0) {
        b = a % 10; //extract a digit
        sum = sum + b; //adding the digits
        a = a / 10; //remained number
      }
      Console.WriteLine("The sum of the digits is: " + sum);
    }
  }
}

Output

The sum of the digits is: 18

Explanation

Inital value of a (input number): a = 567

Iteration 1:
	b = a%10 → 567%10 = 7	
	sum = sum+b → 0+7 = 7
	a = a/10 → 567/10 = 56

Iteration 2:
	b = a%10 → 56%10 = 6
	sum = sum+b → 7+6 = 13
	a = a/10 → 56/10= 5

Iteration 3:
	b = a%10 → 5%10 = 5
	sum = sum+b → 13+5= 18
	a = a/10 → 5/10 = 0

Now, the value of a is "0", condition will be fasle
Output will be 18.	

C# Basic Programs »

All C#.Net Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.