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 = 567Iteration 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.
Consider the program:
Output
Explanation: