Loops
Compare a number with its reversed digits to recognize numeric palindromes.
Complete program
#include <stdio.h>
int main(void) {
int original, remaining, reversed = 0;
printf("Number (0 to 999999): ");
if (scanf("%d", &original) != 1 || original < 0 || original > 999999) return 1;
remaining = original;
do {
reversed = reversed * 10 + remaining % 10;
remaining /= 10;
} while (remaining);
puts(original == reversed ? "Palindrome" : "Not a palindrome");
return 0;
}
Opens a new program without replacing your saved code. Press Run when you are ready.
How it works
Keep the original value because the digit-extraction loop consumes its working copy. Comparing the final reversed value with the original answers the question.
This definition treats input as a nonnegative number, not a text string: leading zeroes are discarded during conversion. Try 0, 121, and 120. A word palindrome needs string indexing and possibly rules for capitalization and spaces.
Sample input
1221Enter these values when prompted. The transcript below includes typed responses.
Expected output
Number (0 to 999999): 1221
PalindromeConcepts to practice
- Preserving state
- Equality
- Digit loops
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.