Reverse the Digits of a Number Using a do-while Loop in C

This program reverses the digits of a given number using a do-while loop.

C Program

#include <stdio.h>

int main() {
    int num, reversed = 0, remainder;

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

    do {
        remainder = num % 10;
        reversed = reversed * 10 + remainder;
        num = num / 10;
    } while (num != 0);

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

    return 0;
}

Explanation

  • A do-while loop is used instead of a while loop so the body runs at least once, which correctly handles a single-digit input as well.
  • Each iteration peels off the last digit with num % 10 and appends it to reversed by shifting the existing digits left (reversed * 10) and adding the new digit.
  • num / 10 (integer division) drops the digit that was just processed.
  • The loop continues until num becomes 0, meaning every digit has been moved into reversed in reverse order.

Sample Output

Enter a number: 12345
Reversed number: 54321

Leave a Comment