OverIQ.com

C Program to reverse the digits of a number

Last updated on July 27, 2020


The following is a C program to reverse the digits of a number:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/********************************************
 * Program to reverse the digits of a number
*********************************************/

#include<stdio.h> // include stdio.h

int main() 
{
    long int num, rev = 0;
    int rem;

    printf("Enter a number: ");
    scanf("%ld", &num);

    while(num != 0)
    {
        rem = num % 10;        // get the last digit of num
        rev = rev * 10 + rem;  // reverse the number
        num = num / 10;        // remove the last digit from num
    }

    printf("%ld", rev);

    return 0;
}

Expected Output: 1st run:

1
2
Enter a number: 1728
8271

2nd run:

1
2
Enter a number: 456123
321654

How it works #

The following table demonstrates the algorithm we used to reverse the digits of the a given number, assuming n = 1728:

Iteration remainder rev num
After 1st iteration rem = 1728%10 = 8 rev = 0*10+8 = 8 num = 1728/10 = 172
After 2nd iteration rem = 172%10 = 2 rev = 8*10+2 = 82 num = 172/10 = 17
After 3rd iteration rem = 17%10 = 7 rev = 82*10+7 = 827 num = 17/10 = 1
After 4th iteration rem = 1%10 = 1 rev = 827*10+1 = 8271 num = 1/10 = 0

Recommended Reading: