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-whileloop is used instead of awhileloop 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 % 10and appends it toreversedby 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
numbecomes 0, meaning every digit has been moved intoreversedin reverse order.
Sample Output
Enter a number: 12345
Reversed number: 54321