Q:

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

belongs to collection: C# Basic Programs | Looping programs

0

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

Example:

Input: 567
Output: 18

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

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.	

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# program to reverse digits of a given number... >>
<< Define Fibonacci series - Write a program to print...