Thread: I can't quite get the logic behind this code...

1. I can't quite get the logic behind this code...

i'm still very new at this, and i found this code that could help me on my project. but i can't quite get the logic behind it. the code is like this :

Code:
```#include<stdio.h>
void main()
{
int n  , i ;
int stk[15] , top = 0;
printf("Enter the number :");
scanf("%d" , &n);
while( n > 0 )
{
i = n % 10;
stk[++top] = i;
n = n / 10;

}
while(top)printf("%d " , stk[top--]);
}```
so basically, that program will seperates number into it's individual digits.
the stuff that i don't quite get is this :

- why using a loop ? can it be solve by logical if ?
- why the code is not working if i 'change stk[++top] = i' into 'stk[top++] = i'
- what is the meaning of "while(top)printf("%d " , stk[top--])" ? i mean why use 'while' ? and why you use 'top--' ?

that is all. thx !

1. You need a loop because you need to do the bit inside the loop more than once. An if only does things once, never multiple times.
2. Do you know what the difference is between ++top and top++? Why not look it up?
3. Again, while is a loop, because the part inside the loop needs to be done more than once.
4. If you sit down with a piece of paper, dream up a number for n, and be the computer and run the program yourself, you'd probably answer all your questions.

2. Ok so the &#37; operator is taking the remainder of the operation n % 10, right? So lets walk through the code by hand a little bit (and get into the habit of breaking out a sheet of paper and doing this sometime. Eventually you will be able to conceptualize this in your head... but don't try to take shortcuts).

user input: 165

Is n > 0? Yes
i = 165 % 10
i = 5.
stk contains ['5',...] ("..." is used since the rest of stk is technically undefined data)
n = n / 10
n = 16 (int math, remember)

Is 16 > 0? Yes
i = 16 % 10
i = 6
stk contains [5,6,...]
n = 16/10
n = 1

Is 1 > 0? Yes
i = 1 % 10
i = 1
stk contains [5,6,1,...]
n = 1/10
n = 0

Is 0 > 0? No
break

Now since the array contains [5,6,1,...] and we want to print out the numbers logically, they will need to be printed out in reverse, right?

That is why top is decremented during the output process.

3. wow ! thx guys ! ok i will get used to with the paper thingy.... hehehe ! thx !

4. Yeah no problem. In honesty, even the best of us have random piles of doodles and iterations of loops on our desk near our keyboard. There is no shame in stepping through your own code.

5. >even the best of us have random piles of doodles and iterations of loops on our desk near our keyboard
One might argue that we're the best because of those doodles and iterations of loops.

6. I can argue that. Plus I must say I make a mighty fine doodle. My labels may be unintelligible to anyone besides me. But the doodles are high quality.