### Thread: [While Loop] Program to Reverse the Digits of a Number

1. #### [While Loop] Program to Reverse the Digits of a Number

Code:
```// Program to reverse the digits of a number

#include <stdio.h>

int main (void)
{
int iNum, iRight;

scanf ("%i", &iNum);

while (iNum != 0)
{
iRight = iNum % 10;
printf ("%i", iRight);
iNum /= 10;
}

printf ("\n");

return 0;
}```
Hi guys,

I'm mostly just beginning C and self-studying with S. Kochan's book, Programming in C (3rd Edition).

I understand until where the code extracts and prints the rightmost digit but I seem confused as to the purpose of this line:

iNum /= 10;

I do know it means iNum = iNum / 10; but I can't quite grasp how it works in the algorithm or "why" it should be there.

2. > but I can't quite grasp how it works in the algorithm or "why" it should be there.
You know you can try
Code:
```  while (iNum != 0)
{
iRight = iNum % 10;
printf ("%i", iRight);
/* commented out iNum /= 10; */
}```
or even
Code:
```  while (iNum != 0)
{
iRight = iNum % 10;
printf ("%i", iRight);
iNum /= 5;
}```
- why there is a division
- why the divisor has to be 10
3. >> why there is a division
Program enters an infinite loop of the last digit.

>> why the divisor has to be 10
Let's see, here's a try of what I think happens.

Say I enter 5678. This part of the code...

iRight = iNum % 10;
printf ("%i", iRight);

...gives a remainder of 8 and prints it first.

iNum /= 10;
• Divides the user-inputted iNum value, 5678 by 10 resulting to the integer value of 567 which is now the new value of iNum.
• Since 567 is not equal to 0, the program executes the body of the while loop using the new value 567 giving a remainder of 7 and prints it as the next digit.
• 567 is divided by 10, resulting to 56, which still holds true for the condition, remainder 6, prints.
• 56 divided by 10 gives a new value for iNum which is now 5.
• 5 % 10 is 5, prints. Since 5/10 is 0 by rules of integer division, the loop terminates.

-----
Thank you for the tips, salem. Is my understanding somehow near? >.<