C Program to Reverse a Given Number


This is a C program to reverse a given integer.

Problem Description

This C program accepts an integer and reverse it.

Problem Solution

1. Take the number which you have to reverse as the input.
2. Obtain its quotient and remainder.
3. Multiply the separate variable with 10 and add the obtained remainder to it.
4. Do step 2 again for the quotient and step 3 for the remainder obtained in step 4.
5. Repeat the process until quotient becomes zero.
6. When it becomes zero, print the output and exit.

Program/Source Code

Here is source code of the C program to reverse a given number. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  2. #include <stdio.h>
  4. void main()
  5. {
  6.     long  num, reverse = 0, temp, remainder;
  8.     printf("Enter the number\n");
  9.     scanf("%ld", &num);
  10.     temp = num;
  11.     while (num > 0)
  12.     {
  13.         remainder = num % 10;
  14.         reverse = reverse * 10 + remainder;
  15.         num /= 10;
  16.     }
  17.     printf("Given number = %ld\n", temp);
  18.     printf("Its reverse is = %ld\n", reverse);
  19. }
Program Explanation

1. Take the number which you have to reverse as the input and store it in the variable num.
2. Copy the input number to the another variable temp.
3. Firstly initialize the variable reverse to zero.
4. Obtain the remainder of the input number.
5. Multiply the variable reverse with 10 and add the Obtained remainder to it and store the result in the same variable.
6. Obtain the quotient of the input number and considering this as input number repeat the steps as mentioned above until the obtained quotient becomes zero.
7. When it becomes zero, print the given number and its reverse using variables temp and reverse respectively as ouput.

Runtime Test Cases
Enter the number
Given number   = 567865
Its reverse is = 568765
Enter the number
Given number   = 00001
Its reverse is = 10000

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Simple C Programs, go to Simple C Programs. If you wish to look at programming examples on all topics, go to C Programming Examples.

Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn