Can't understand the math behind the code

Viewed 52

when I calculate it manually, I get total nonsense. n is always !=0

Console.Write("Input  a number(integer): ");

int n = Convert.ToInt32(Console.ReadLine());
int sum = 0;

while (n != 0) 
{
  sum += n % 10;
  n   /= 10;
}

Console.WriteLine("Sum of the digits of the said integer: " + sum);
2 Answers

Sometimes in informatics, you need to remember basic school, when you were taught how decimal numbers work. Counting with your fingers, basically. You were not knowing that divisions lead to fractions, so you calculated divisions with a remainder, e.g.

  • 7:4 = 1 R 3
  • 10:3 = 3 R 1

Likewise, you might accidentally divide by 10:

  • 231:10 = 23 R 1
  • 142:10 = 14 R 2
  • 357:10 = 35 R 7

Note how the remainder is always the last digit of the number. That's what %10 gives you. Also note that the number before R is the result of /10 gives you (n/=10; means n=n/10;). This happens because the decimal number system has base 10.

If you repeatedly do that, you get

  • 75312:10 = 7531 R 2
  • 7531:10 = 753 R 1
  • 753:10 = 75 R 3
  • 75:10 = 7 R 5
  • 7:10 = 0 R 7

If you sum up all the numbers after R, that's the result. We call it cross sum, cross total or sum of digits.

Besides math, check out Eric Lipperts great post about how to debug small programs. It will be valuable for you.

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

Related