Complementary task for topic: 4
M Nemeth · 2023-08-29 15:21:04.617219'
Functions: Palindrome Check
Functions: Palindrome Check
Write a C function is_palindrome that takes an integer as input and returns 1 if the number is a palindrome (reads the same forwards and backwards), and 0 otherwise.
Hint:
Solution
#include
// Function to check if a number is a palindrome
int is_palindrome(int num) {
int reversed = 0, original = num;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return (original == reversed);
}
int main() {
int num;
printf("Enter a number to check if it is a palindrome: ");
scanf("%d", &num);
if (is_palindrome(num))
printf("%d is a palindrome.\n", num);
else
printf("%d is not a palindrome.\n", num);
return 0;
}
Explanation
The is_palindrome function checks if a given number is a palindrome by reversing its digits and comparing the reversed number with the original number. If they are the same, the number is a palindrome. The main function takes a number as input, calls the is_palindrome function, and prints the result.