C Program – Reverse a Number - Digits Reversal Explained

Reverse a Number

This program takes an integer input from the user and reverses its digits. For example, input 12345 yields output 54321. We accomplish this by repeatedly taking the last digit from the original number and appending it to a new reversed number.

#include <stdio.h>
int main() {
    int n, rev = 0, rem;          // n is the input, rev holds the reversed number, rem stores each digit
    printf("Enter an integer: ");
    scanf("%d", &n);
    // Loop until all digits are processed
    while (n != 0) {
        rem = n % 10;             // Take the last digit
        rev = rev * 10 + rem;     // Append it to the reversed number
        n /= 10;                  // Remove the last digit from n
    }
    printf("Reversed number = %d\n", rev);
    return 0;
}
Enter an integer: 12345
Reversed number = 54321
        

The key idea is to repeatedly extract the last digit of the number using the modulus operator (%). Each extracted digit is appended to the reversed number by multiplying the current reversed value by 10 (to make space for the new digit) and adding the digit. After processing, the original number becomes zero and the reversed number holds the digits in the opposite order.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...