Loading your workspace…
Loading your workspace…
Read a positive integer, find the sum of its digits, reverse it, and report whether it is a palindrome.
#include <stdio.h>
int main(void) {
int number, copy, digit, sum = 0, reversed = 0;
printf("Enter a positive integer:\n");
if (scanf("%d", &number) != 1 || number < 1) {
printf("Error: enter a positive integer\n");
return 1;
}
copy = number;
while (copy > 0) {
digit = copy % 10;
sum += digit;
reversed = reversed * 10 + digit;
copy /= 10;
}
printf("Sum of digits: %d\n", sum);
printf("Reversed: %d\n", reversed);
if (reversed == number) {
printf("%d is a palindrome\n", number);
} else {
printf("%d is not a palindrome\n", number);
}
return 0;
}
Input
121Output
Enter a positive integer:
Sum of digits: 4
Reversed: 121
121 is a palindromeInput
1234Output
Enter a positive integer:
Sum of digits: 10
Reversed: 4321
1234 is not a palindromeThe loop peels off the last digit with the remainder operator and removes it with integer division by 10. Building reversed as reversed × 10 + digit appends each digit to the right end of the new number.
A number is a palindrome when it reads the same backwards, so comparing the reversed value with the original answers the question directly. Trailing zeros lose their place in a reversal, e.g. 120 reverses to 21, which is a known limitation of this method.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
121
Expected output
Enter a positive integer: Sum of digits: 4 Reversed: 121 121 is a palindrome
1234
Expected output
Enter a positive integer: Sum of digits: 10 Reversed: 4321 1234 is not a palindrome
The last digit of the number.
It removes the last digit by integer division.
It reverses to 21, which is not equal to 120, so the check correctly says no.
The loop destroys its variable, and the original is needed for the palindrome comparison.
Yes. A reversal has at most as many digits as the input, so a large input whose reverse exceeds the int limit overflows.
Back to all RCU 21BCA1C1P lab programs.