C Program to Reverse a Number

C Program to Reverse a Number

Reversing a number is a fundamental exercise in C programming. It helps beginners understand loops, arithmetic operations, and how numbers can be manipulated at the digit level. In this tutorial, we will write a complete C program to reverse a number using both iterative and recursive methods. Each line will be explained carefully, and common mistakes will be highlighted. By the end, you will know how to reverse any integer using C and understand the reasoning behind each step.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Reversing a number is a practical problem that introduces important programming concepts like loops, recursion, modulo operations, and integer division. Processing each digit individually strengthens your understanding of how numbers are stored and manipulated in memory. It also lays the foundation for more complex problems like palindrome checking or digit-based algorithms.

Iterative Method to Reverse a Number

The iterative approach extracts each digit from the original number and constructs a new number in reverse order using a loop.

#include <stdio.h>

int main() {

    int num, reversed = 0, remainder;

    printf("Enter an integer: ");
    scanf("%d", &num);

    while (num != 0) {

        remainder = num % 10;
        reversed = reversed * 10 + remainder;
        num = num / 10;

    }

    printf("Reversed number: %d\n", reversed);

    return 0;

}

Here, num stores the input number, reversed stores the reversed number, and remainder temporarily holds each digit. The while loop continues until num becomes zero. The modulo operator % extracts the last digit, which is then added to reversed after shifting its previous digits by multiplying by 10. Integer division / removes the last digit from num. After the loop, reversed holds the reversed number, which is printed using printf().

Step-by-Step Explanation

When the user enters a number like 1234, the loop works as follows:

  1. First iteration: remainder = 1234 % 10 → remainder = 4. Then reversed = 0 * 10 + 4 → reversed = 4. Finally, num = 1234 / 10 → num = 123.
  2. Second iteration: remainder = 123 % 10 → remainder = 3. reversed = 4 * 10 + 3 → reversed = 43. num = 123 / 10 → num = 12.
  3. Third iteration: remainder = 12 % 10 → remainder = 2. reversed = 43 * 10 + 2 → reversed = 432. num = 12 / 10 → num = 1.
  4. Fourth iteration: remainder = 1 % 10 → remainder = 1. reversed = 432 * 10 + 1 → reversed = 4321. num = 1 / 10 → num = 0.

The loop ends, and the program prints 4321, which is the reverse of the original number.

Recursive Method to Reverse a Number

Recursion is another way to reverse a number, which calls a function repeatedly until a base condition is met. The recursive approach is elegant and often preferred by experienced programmers for its simplicity in logic.

#include <stdio.h>

int reverseNumber(int num, int reversed) {

    if (num == 0)
        return reversed;

    return reverseNumber(num / 10, reversed * 10 + num % 10);

}

int main() {

    int num;

    printf("Enter an integer: ");
    scanf("%d", &num);

    int reversed = reverseNumber(num, 0);
    printf("Reversed number (recursive): %d\n", reversed);

    return 0;

}

In this program, reverseNumber() is a recursive function. It takes two arguments: num, the remaining number to process, and reversed, the reversed number constructed so far. The base case occurs when num becomes zero, at which point the function returns reversed. Otherwise, the function calls itself with num / 10 (removing the last digit) and reversed * 10 + num % 10 (adding the extracted digit). This continues until all digits are processed.

How the Recursive Function Works

Suppose the input is 1234. The function operates like this:

  1. Call 1: reverseNumber(1234, 0) → calls reverseNumber(123, 4)
  2. Call 2: reverseNumber(123, 4) → calls reverseNumber(12, 43)
  3. Call 3: reverseNumber(12, 43) → calls reverseNumber(1, 432)
  4. Call 4: reverseNumber(1, 432) → calls reverseNumber(0, 4321)
  5. Base case reached → returns 4321

This shows that recursion naturally processes digits from last to first without using explicit loops.

Common Beginner Mistakes

When reversing a number, beginners often make these mistakes:

  • Forgetting to initialize reversed to zero, which can lead to incorrect results.
  • Using the wrong data type. int may overflow for very large numbers, so a larger type like long long int is safer.
  • Forgetting that integer division truncates decimals, which is necessary for correctly removing digits.
  • In recursive implementations, omitting a base case, which causes infinite recursion and crashes the program.

To avoid these issues, always initialize variables, choose an appropriate data type, handle integer division carefully, and include a proper base case for recursion.

FAQs

Q1: Can this program reverse negative numbers?
Yes, both iterative and recursive methods can handle negative numbers. The negative sign remains attached to the reversed value.

Q2: Which method is better, iterative or recursive?
For beginners, iterative is simpler and easier to debug. Recursion is elegant but can be harder to follow. For very large numbers, iterative avoids stack overflow issues.

Q3: Can I reverse floating-point numbers?
No, these methods work only for integers. Floating-point numbers require string conversion or separate handling of integer and fractional parts.

Q4: What happens if the number is very large?
If the reversed number exceeds the int range, overflow occurs. Using long long can prevent this issue.

Conclusion

Reversing a number in C is a classic exercise that teaches loops, recursion, and arithmetic operations. Both iterative and recursive methods are effective, and understanding each approach deepens your grasp of C programming fundamentals. By practicing these techniques, you can confidently handle similar problems like palindromes or digit analysis. Keep experimenting with numbers of different lengths and signs to strengthen your skills.

References & Additional Resources

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language. 2nd Edition, Prentice Hall, 1988.
  2. GeeksforGeeks: Reverse a Number in C – Multiple examples and explanations.
  3. Programiz: C Programming Examples – Beginner-friendly C programs.
  4. TutorialsPoint: Loops and Recursion in C – Guide to recursion and loops.
  5. Stack Overflow: Integer Overflow in C – Handling large numbers safely.
Scroll to Top