Implementation of isPalindrome(int) Function

To implement an isPalindrome(int) function in C that checks whether an integer is a palindrome (reads the same forwards and backwards), you can reverse the integer and compare it with the original. Here's an example of how to implement the isPalindrome() function:

Example:


#include <stdio.h>

// Function to check if an integer is a palindrome
int isPalindrome(int num) {
    int originalNum = num;
    int reversed = 0;

    while (num > 0) {
        int digit = num % 10;
        reversed = reversed * 10 + digit;
        num /= 10;
    }

    return originalNum == reversed;
}

int main() {
    int number1 = 12321; // Palindrome
    int number2 = 12345; // Not a palindrome

    if (isPalindrome(number1)) {
        printf("%d is a palindrome.\n", number1);
    } else {
        printf("%d is not a palindrome.\n", number1);
    }

    if (isPalindrome(number2)) {
        printf("%d is a palindrome.\n", number2);
    } else {
        printf("%d is not a palindrome.\n", number2);
    }

    return 0;
}
    

In this example:

  • The isPalindrome() function takes an integer num as its parameter.
  • It first stores the original value of num in the originalNum variable.
  • Inside the while loop, the function reverses num by repeatedly extracting the last digit using the modulo operator % and adding it to the reversed variable. It then removes the last digit from num by dividing it by 10.
  • Finally, the function returns 1 if originalNum is equal to reversed, indicating that the integer is a palindrome, and 0 otherwise.
  • In the main() function, two numbers (12321 and 12345) are checked using the isPalindrome() function, and the result is printed.

Output:


12321 is a palindrome.
12345 is not a palindrome.
    

You can use this isPalindrome() function to check whether any integer is a palindrome by passing it as an argument to the function.