[While Loop] Program to Reverse the Digits of a Number
Discuss [While Loop] Program to Reverse the Digits of a Number in the C Programming forum on Dev Shed. [While Loop] Program to Reverse the Digits of a Number C programming forum discussing all C derivatives, including C#, C++, Object-C, and even plain old vanilla C. These languages are low level languages, and used on projects such as device drivers, compilers, and even whole computer operating systems.
Posts: 45
Time spent in forums: 18 h 57 m 8 sec
Reputation Power: 4
[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;
printf ("Enter your number.\n");
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.
Posts: 45
Time spent in forums: 18 h 57 m 8 sec
Reputation Power: 4
>> 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? >.<