Loops
Extract decimal digits from a nonnegative integer and rebuild them in reverse order.
Complete program
#include <stdio.h>
int main(void) {
int n, reversed = 0;
printf("Number (0 to 999999): ");
if (scanf("%d", &n) != 1 || n < 0 || n > 999999) return 1;
do {
reversed = reversed * 10 + n % 10;
n /= 10;
} while (n != 0);
printf("Reversed: %d\n", reversed);
return 0;
}
Opens a new program without replacing your saved code. Press Run when you are ready.
How it works
Remainder by ten extracts the last digit; integer division by ten removes it. Multiplying the growing result by ten makes room for the extracted digit.
Leading zeroes are not part of an integer value, so reversing 12340 prints 4321. Use strings when the exact sequence of characters, including zeroes, must be preserved. The input bound keeps the reconstructed result representable.
Sample input
12340Enter these values when prompted. The transcript below includes typed responses.
Expected output
Number (0 to 999999): 12340
Reversed: 4321Concepts to practice
- do / while
- Integer division
- Digit extraction
Predict a different input or change one value, then compare the result with your prediction. Keep changes within the documented bounds and read warnings before trusting an answer.