Palindrome Check Program in C
This program checks if a given number is a palindrome. A palindrome is a number that remains the same when its digits are reversed. For example, 121 and 12321 are palindromes.
Program Structure and Explanation
The program follows these steps:
- Prompt the user to enter a number.
- Reverse the digits of the entered number.
- Compare the reversed number with the original number.
- Print a message indicating whether the number is a palindrome.
Documentation
The program includes detailed comments to explain each part of the code.
Code
#include <stdio.h>
// Function to check if a number is a palindrome
int isPalindrome(int number);
int main() {
int number;
// Prompt the user to enter a number
printf("Enter a number: ");
scanf("%d", &number);
// Check if the number is a palindrome
if (isPalindrome(number)) {
printf("%d is a palindrome.\n", number);
} else {
printf("%d is not a palindrome.\n", number);
}
return 0;
}
/**
* Function to check if a number is a palindrome
* @param number The number to check
* @return 1 if the number is a palindrome, 0 otherwise
*/
int isPalindrome(int number) {
int originalNumber = number; // Store the original number
int reversedNumber = 0; // Initialize the reversed number
int remainder;
// Reverse the digits of the number
while (number != 0) {
remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number /= 10;
}
// Check if the reversed number is equal to the original number
if (originalNumber == reversedNumber) {
return 1;
} else {
return 0;
}
}
Explanation of the Code
#include <stdio.h>: Includes the standard input-output library.int isPalindrome(int number);: Declares the function prototype for checking if a number is a palindrome.int main(): The main function where the program execution begins.int number;: Declares a variable to store the user input.printf("Enter a number: ");: Prompts the user to enter a number.scanf("%d", &number);: Reads the input number from the user.if (isPalindrome(number)): Calls theisPalindromefunction and checks the result.printf("%d is a palindrome.\n", number);: Prints a message if the number is a palindrome.printf("%d is not a palindrome.\n", number);: Prints a message if the number is not a palindrome.int isPalindrome(int number): Defines the function to check if a number is a palindrome.int originalNumber = number;: Stores the original number for later comparison.int reversedNumber = 0;: Initializes the reversed number.int remainder;: Declares a variable to store the remainder of division.while (number != 0): Loops until the number becomes 0.remainder = number % 10;: Gets the last digit of the number.reversedNumber = reversedNumber * 10 + remainder;: Builds the reversed number.number /= 10;: Removes the last digit from the number.if (originalNumber == reversedNumber): Checks if the reversed number is equal to the original number.return 1;: Returns 1 if the number is a palindrome.return 0;: Returns 0 if the number is not a palindrome.
