Reverse of a five digit number

If a five-digit number is input through the keyboard, write a program in C to reverse the number.

Program

#include<stdio.h>
#include<conio.h>
void main()
{
long int num, rev_num;
int next;

printf("Enter a five digit number\t:");
scanf("%ld", &num);

rev_num = num % 10;
next = (num / 10) % 10;
rev_num = (rev_num * 10) + next;
next = (num / 100) % 10;
rev_num = (rev_num * 10) + next;
next = (num / 1000) % 10;
rev_num = (rev_num * 10) + next;
next = (num / 10000) % 10;
rev_num = (rev_num * 10) + next;

printf("Reversed number is = %ld",rev_num);

getch();
}

Output

Enter a five digit number       :23456
Reversed number is = 65432

Explanation

A five digit number is taken as an input from the user in the variable named 'num'. %ld is the format specifier used for long int data type. A variable named 'rev_num' is used to carry the reverse of the number.

The logic used to find the reverse of a number is as follows:
take out the last (rightmost) digit of the number.
Give it to rev_num.
Take out the 2nd digit from right.
Now multiply rev_num by 10 and add this new digit to it.
Do this till the first digit.


Let us understand this with the help of an example:
Let, num = 67584

rev_num = num % 10; rev_num = 67584 % 10 = 4
(Last digit is extracted and assigned to rev_num)
next = (num / 10) % 10; next = (67584/10) % 10 = 6758 % 10 = 8
(Second last digit is extracted and stored in 'next')
rev_num = (rev_num * 10) + next; rev_num = (4 * 10) + 8 = 40 + 8 = 48
(rev_num is multiplied by 10 and value extracted is added to it.)
next = (num / 100) % 10; next = (67584/100) % 10 = 675 % 10 = 5
(above procedure is repeated)
rev_num = (rev_num * 10) + next; rev_num = (48 * 10) + 5 = 480 + 5 = 485
next = (num / 1000) % 10; next = (67584/1000) % 10 = 67 % 10 = 7
rev_num = (rev_num * 10) + next; rev_num = (485 * 10) + 7 = 4850 + 7 = 4857
next = (num / 10000) % 10; next = (67584/10000) % 10 = 6 % 10 = 6
rev_num = (rev_num * 10) + next; rev_num = (4857 * 10) + 6 = 48570 + 6 = 48576

rev_num = 48576