Lets now decode the code step by step
Step 1:
This part of code
sum += n % 10;
is equivalent to
sum = sum + n%10;
This part of code is
n /= 10;
is equivalent to
n =n/10;
Step 2:
Replace your code with the above one
Console.Write("Input a number(integer): ");
int n = Convert.ToInt32(Console.ReadLine());
int sum = 0;
while (n != 0)
{
sum =sum + n%10 //sum += n % 10;
n =n/10; //n /= 10;
}
Console.WriteLine("Sum of the digits of the said integer: " + sum);
Step 3: Lets now decode your code with an example
Note : % returns reminder and / returns quotient
Let n be 125
loop 1:
n!=0, hence the condition is true and we enter inside the while loop
sum = 0 + 5 (125%10) => sum =5
n = 12 (n/10) => n=12
loop 2 :
new n is 12
n!=0 again condition is true we enter inside the while loop
The value of sum was 5 during pervious loop
sum =5(pervious value) + 2(12%10) => sum =5+2 => sum =7
n = 1 (12/10)
loop 3:
n is 1, the condition is true hence the next steps
sum = 7(previous value) + 1(1%10) => sum = 7+1 => sum=8
n = 0 (1/10);
Now the condition fails. Now we can print the sum. When we look at step 3 we can able to see we are separating each digit of a number from backward.
n%10 will gives us each digit from backward 5,2,1 for 125.
Thus the code gives the sum of all digits. Hope this helps. Feel free to ask your question if you find any difficulties in understanding the Explanation