Question: I'm learning C and I am having a hard time understanding loops and the usage of modulo. I know Loops are used to shorten up the program and Modulo's are used to get out the remainder. My assignment was to "Write a C program to find the sum of an individual positive integer".

I just spent few hours trying to understand this problem. I experimented too. 

```

    int  n,d=0,s=0;
    printf("\nEnter a number\n\n");
    scanf("%d",&n);
```

`while(n>0)
 { 
 d = n%10;
 s = s+d;
 n = n/10;
 }

printf("\n sum of the individual digits = %d",s);`

**My questions are:** 

Can anyone help me understand the flow of this program? Why is Modulo being used? and Why is there a n = n/10

Experiements I've done:

When I removed d = n%10; line the output prints out the digits seperatley. thus it's not calculating. 

i.e 123 = 6 --> It's giving me 136

When I removed the line n = n/10 It's not showing me an output. The printf statement has a parameter 's' 

Thanks in Advance!

Answer: 
Taking the modulo in `d = n % 10` makes `d` equal to the last digit of `n` in base 10. `n = n / 10` removes the last digit from `n`. 

Modulo is essentially taking the remainder, so let's say `n = 123`. Then `n / 10` is `12` and `n % 10` is `3`. 

Removing the `n = n / 10` means that `n` doesn't change between each run of the loop, so the loop condition `n > 0` is always true and therefore the loop keeps going until you manually kill the program. 

Here is a trace of the program with `n = 123`. Initially `d` and `s` are both zero.

```
 while (n > 0) {  // n is 123, which is greater than zero, so we enter the loop
     d = n % 10;  // 123 % 10 is 3, so d is now 3
     s = s + d;   // 0 + 3 is 3, so s is now 3
     n = n / 10;  // 123 / 10 is 12, so n is now 12.
 }                // go back to the top of the loop
 while (n > 0) {  // n is 12, which is still greater than zero
     d = n % 10;  // 12 % 10 is 2, so d is now 2
     s = s + d    // 3 + 2 is 5, so s is now 5
     n = n / 10;  // 12 / 10 is 1, so n is now 1
 }                // go back to the top again
 while (n > 0) {  // n is 1, which is still greater than zero
     d = n % 10;  // 1 % 10 is 1, so d is now 1
     s = s + d;   // 5 + 1 is 6, so s is now 6
     n = n / 10;  // 1 / 10 is 0, so n is now 0
 }                // go back to the top
 while (n > 0) {  // n is 0, which is not greater than zero, so we skip
                  // to after the loop body
 printf("\n sum of the individual digits = %d",s);

```
Try these:

```
int n = 12;
printf("%d\n", n / 10);

int j = 12;
printf("%d\n", j % 10);

int x = 13;
x = x / 10;   // right hand side of "=" get evaluated first
printf("%d\n", x);

```

Observe the output in each case.

Regarding your last point:

```
while (n > 0)
{
    // some code.
}

```

This means: While the value of `n` is greater than zero run `some code`. Now, if you don't change `n`, `some code` will run for eternity.
HTH.