Exploring Palindromes in C: Numbers and Strings
Welcome to C-Language-Series #141! In this installment, we're diving into a classic programming challenge: implementing a palindrome check in C. Whether you're working with numbers or strings, identifying sequences that read the same forwards and backwards is a great way to practice fundamental C concepts like loops, conditional statements, and string manipulation.
What is a Palindrome?
A palindrome is a sequence of characters or numbers that reads the same forwards and backwards. It's a symmetrical pattern that appears in various forms across languages and mathematics.
- Number Examples:
121,12321,9009 - String Examples:
"madam","level","refer"
For our C implementations, we'll focus on exact matches for simplicity. However, the core principles can be extended to handle more complex cases like case-insensitivity (e.g., "Madam" is a palindrome) or ignoring special characters/spaces (e.g., "A man, a plan, a canal: Panama").
1. Checking for Palindrome Numbers in C
Determining if a number is a palindrome involves reversing the number and then comparing the reversed version with the original. If they are identical, the number is a palindrome.
The Logic for Palindrome Numbers
The core idea is to extract digits from the original number one by one, using the modulo operator (%)
to get the last digit and integer division (/) to remove it. We then build a new number that is the reverse of the original.
- Store the original number in a temporary variable, as we'll modify it during the reversal process.
- Initialize a variable, say
reversedNumber, to 0. This variable will hold the reversed number. - Loop while the temporary number is greater than 0:
- Extract the last digit using:
remainder = temp % 10; - Build the reversed number:
reversedNumber = (reversedNumber * 10) + remainder; - Remove the last digit from the temporary number:
temp /= 10;
- Extract the last digit using:
- Finally, compare
originalNumberwithreversedNumber. If they match, it's a palindrome.
C Code Example: Palindrome Number
Here's a C program that checks if an integer entered by the user is a palindrome:
#include <stdio.h>
int main() {
int n, originalNumber, reversedNumber = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
originalNumber = n; // Store the original number for comparison later
// Loop to reverse the number
while (n != 0) {
remainder = n % 10; // Get the last digit (e.g., for 123, remainder is 3)
reversedNumber = reversedNumber * 10 + remainder; // Build the reversed number (0*10+3=3, 3*10+2=32, 32*10+1=321)
n /= 10; // Remove the last digit from n (e.g., 123 becomes 12, then 1, then 0)
}
// Check if the original and reversed numbers are the same
if (originalNumber == reversedNumber) {
printf("%d is a palindrome number.\n", originalNumber);
} else {
printf("%d is not a palindrome number.\n", originalNumber);
}
return 0;
}
Code Explanation for Palindrome Numbers
originalNumber = n;: We save the user's input because the value ofnwill be modified (reduced to 0) during the reversal process.while (n != 0): This loop continues as long as there are digits left innto process.remainder = n % 10;: This extracts the last digit ofn. For example, ifnis 123,remainderwill be 3.reversedNumber = reversedNumber * 10 + remainder;: This line is crucial for building the reversed number. Each extracted digit is appended to the rightmost position ofreversedNumber.n /= 10;: This performs integer division, effectively removing the last digit fromn. For example, ifnwas 123, it becomes 12.- After the loop completes,
originalNumberis compared with the fully constructedreversedNumberto determine if it's a palindrome.
2. Checking for Palindrome Strings in C
Checking if a string is a palindrome requires a different approach than numbers. Instead of reversing the entire string, we can efficiently compare characters from the beginning and the end, moving inwards.
The Logic for Palindrome Strings
This method uses two pointers: one starting at the first character of the string and the other at the last character.
- Initialize a
leftpointer to the beginning of the string (index 0). - Initialize a
rightpointer to the end of the string (indexlength - 1). The string's length is typically obtained using thestrlen()function from<string.h>. - Loop while the
leftpointer is less than therightpointer:- Compare the character at
str[left]with the character atstr[right]. - If they are not equal, the string is not a palindrome. Immediately return
false(or indicate it's not a palindrome). - If they are equal, move the
leftpointer one position to the right (left++) and therightpointer one position to the left (right--).
- Compare the character at
- If the loop completes without finding any mismatched characters, it means all corresponding characters matched, and therefore, the string is a palindrome.
C Code Example: Palindrome String
Here's a C program that checks if a string (up to a certain length) entered by the user is a palindrome:
#include <stdio.h>
#include <string.h> // For strlen() and strcspn()
#include <stdbool.h> // For bool type
// Function to check if a string is a palindrome
bool isPalindromeString(char str[]) {
int length = strlen(str);
int left = 0; // Pointer from the beginning
int right = length - 1; // Pointer from the end
// Loop until the pointers meet or cross
while (right > left) {
if (str[left] != str[right]) {
return false; // Mismatch found, not a palindrome
}
left++; // Move left pointer one step forward
right--; // Move right pointer one step backward
}
return true; // All characters matched, it's a palindrome
}
int main() {
char str[100]; // Declare a character array (string) to store input
printf("Enter a string: ");
// Using fgets for safer input, which reads up to (size-1) characters or until newline
fgets(str, sizeof(str), stdin);
// fgets includes the newline character if present, remove it
str[strcspn(str, "\n")] = 0;
if (isPalindromeString(str)) {
printf("'%s' is a palindrome string.\n", str);
} else {
printf("'%s' is not a palindrome string.\n", str);
}
return 0;
}
Code Explanation for Palindrome Strings
#include <string.h>: This header is essential for using thestrlen()function, which calculates the length of the string, andstrcspn().#include <stdbool.h>: This header allows the use of thebooldata type and boolean constantstrueandfalse, making the code more readable.isPalindromeString(char str[]): We've encapsulated the palindrome checking logic within a dedicated function. This promotes modularity and reusability.int length = strlen(str);: This line gets the actual length of the input string, excluding the null terminator.int left = 0;andint right = length - 1;: These initialize our two pointers, one at the start (index 0) and one at the very end of the string.while (right > left): The loop continues as long as the right pointer is ahead of the left pointer. When they meet or cross, all necessary character comparisons have been made.if (str[left] != str[right]): This is the core comparison. If characters at the current pointers don't match, the string cannot be a palindrome, so we immediately returnfalse.left++; right--;: If the characters match, both pointers move one step towards the center of the string for the next comparison.fgets(str, sizeof(str), stdin);: This is a safer alternative toscanf("%s", ...)for reading strings, as it helps prevent buffer overflows by limiting the number of characters read. It also reads the newline character (`\n`) if the user presses Enter before filling the buffer.str[strcspn(str, "\n")] = 0;: This line is used to remove the trailing newline character thatfgetsmight have included.strcspnfinds the first occurrence of `\n` (or any character in its second argument), and we replace it with the null terminator `0`.
Summary and Key Takeaways
Checking for palindromes is a fundamental exercise in C programming that reinforces understanding of basic data manipulation techniques:
- For Numbers: The primary method involves reversing the number using modulo and division, then comparing the reversed version with the original. This is a great way to practice arithmetic operations and loops.
- For Strings: The most efficient method employs two pointers (one from the start, one from the end) that move towards the center of the string, comparing characters iteratively. This demonstrates effective string traversal and conditional logic.
Both algorithms are efficient and straightforward, providing excellent practice with loops and conditional logic in C.
Mastering these basic algorithms builds a strong foundation for more complex C programming challenges. Practice modifying these examples to handle different edge cases, like negative numbers (which typically aren't considered palindromes but can be handled), floating-point numbers, or strings with spaces and varying capitalization. Stay tuned for the next installment in our C-Language Series!