C Program To Find Palindrome Numbers In A Given Range
Palindrome numbers are fascinating integers that read the same forwards and backward. For example, 121, 55, and 9009 are palindromes. Identifying these numbers within a specific range is a common programming challenge. In this article, you will learn how to write a C program to find all palindrome numbers within a user-defined range.
Problem Statement
The core problem is to efficiently identify numbers within a given numerical range (e.g., from 1 to 1000) that exhibit the palindrome property. This involves checking each number in the range to determine if its digits are symmetrical. The challenge is to implement a robust and clear method for this digit comparison.
Example
Consider finding palindrome numbers in the range from 10 to 100. The expected output would list: 11, 22, 33, 44, 55, 66, 77, 88, 99.
Background & Knowledge Prerequisites
To understand and implement the solutions effectively, readers should have a basic understanding of:
- C Programming Fundamentals: Variables, data types,
if-elsestatements,forandwhileloops. - Arithmetic Operators: Modulo (
%) for extracting digits, division (/) for reducing numbers. - Functions: Defining and calling user-defined functions.
- Input/Output: Using
printfandscanf.
Use Cases or Case Studies
Finding palindrome numbers has several practical and educational applications:
- Educational Puzzles and Challenges: It's a classic problem in introductory programming courses to teach logic and number manipulation.
- Number Theory Exploration: Palindromes are a topic of interest in recreational mathematics and number theory, leading to studies of palindromic primes or squares.
- Algorithmic Practice: It serves as a good exercise for practicing digit manipulation, string processing, and loop control.
- Data Validation (Conceptual): While not directly used for typical data validation, the concept of symmetry check can be analogous to validating patterns in sequences or data entries.
Solution Approaches
We will explore two distinct approaches to determine if a number is a palindrome: one using mathematical digit reversal and another converting the number to a string for comparison.
1. Mathematical Digit Reversal Method
This approach mathematically reverses the digits of a number and then compares the reversed number with the original.
One-line summary: Checks if a number is a palindrome by reversing its digits and comparing the reversed number with the original.
Code Example:
// Palindrome Numbers in Range (Digit Reversal)
#include <stdio.h>
// Function to check if a number is a palindrome
int isPalindrome(int n) {
int originalN = n;
int reversedN = 0;
// Handle negative numbers (not typically considered palindromes)
if (n < 0) {
return 0;
}
// Single digit numbers are palindromes
if (n >= 0 && n < 10) {
return 1;
}
// Reverse the number
while (n > 0) {
int digit = n % 10; // Get the last digit
reversedN = reversedN * 10 + digit; // Add digit to reversed number
n /= 10; // Remove the last digit from n
}
return originalN == reversedN; // Compare original and reversed
}
int main() {
int start_range, end_range;
// Step 1: Get user input for the range
printf("Enter the starting number of the range: ");
scanf("%d", &start_range);
printf("Enter the ending number of the range: ");
scanf("%d", &end_range);
// Step 2: Ensure valid range (start should not be greater than end)
if (start_range > end_range) {
int temp = start_range;
start_range = end_range;
end_range = temp;
}
// Step 3: Print header for results
printf("Palindrome numbers in the range %d to %d are:\\n", start_range, end_range);
// Step 4: Iterate through the range and check each number
for (int i = start_range; i <= end_range; i++) {
if (isPalindrome(i)) {
printf("%d ", i);
}
}
printf("\\n");
return 0;
}
Sample Output:
Enter the starting number of the range: 10
Enter the ending number of the range: 150
Palindrome numbers in the range 10 to 150 are:
11 22 33 44 55 66 77 88 99 101 111 121 131 141
Stepwise Explanation:
isPalindrome(int n)Function:
-
originalNstores the inputnso we can compare it later. -
reversedNis initialized to 0, where the reversed number will be built. - Negative numbers are explicitly handled and returned as non-palindromes. Single-digit numbers (0-9) are considered palindromes.
- A
whileloop continues as long asnis greater than 0: -
n % 10extracts the last digit ofn. -
reversedN = reversedN * 10 + digitshiftsreversedNone position to the left (multiplying by 10) and adds the extracted digit. -
n /= 10removes the last digit fromn, effectively moving to the next digit. - Finally,
originalNis compared withreversedN. If they are equal, the number is a palindrome, and the function returns 1 (true); otherwise, it returns 0 (false).
main()Function:
- It prompts the user to enter the
start_rangeandend_range. - A basic check ensures that
start_rangeis not greater thanend_range, swapping them if necessary. - A
forloop iterates through each integerifromstart_rangetoend_range. - For each
i, theisPalindrome()function is called. - If
isPalindrome(i)returns true (1), the numberiis printed.
2. String Conversion and Comparison Method
This approach converts the integer to a string and then checks if the string is a palindrome by comparing characters from both ends.
One-line summary: Converts the number to a string and then checks if the string reads the same forwards and backward using two pointers.
Code Example:
// Palindrome Numbers in Range (String Conversion)
#include <stdio.h>
#include <string.h> // For strlen
#include <stdlib.h> // For sprintf
// Function to check if a number is a palindrome using string conversion
int isPalindromeString(int n) {
char str[20]; // Buffer to hold the string representation of the number
// Handle negative numbers
if (n < 0) {
return 0;
}
// Convert integer to string
sprintf(str, "%d", n);
int length = strlen(str);
int i = 0; // Pointer from the start
int j = length - 1; // Pointer from the end
// Compare characters from both ends towards the middle
while (i < j) {
if (str[i] != str[j]) {
return 0; // Not a palindrome
}
i++;
j--;
}
return 1; // It is a palindrome
}
int main() {
int start_range, end_range;
// Step 1: Get user input for the range
printf("Enter the starting number of the range: ");
scanf("%d", &start_range);
printf("Enter the ending number of the range: ");
scanf("%d", &end_range);
// Step 2: Ensure valid range
if (start_range > end_range) {
int temp = start_range;
start_range = end_range;
end_range = temp;
}
// Step 3: Print header for results
printf("Palindrome numbers in the range %d to %d are:\\n", start_range, end_range);
// Step 4: Iterate through the range and check each number
for (int i = start_range; i <= end_range; i++) {
if (isPalindromeString(i)) {
printf("%d ", i);
}
}
printf("\\n");
return 0;
}
Sample Output:
Enter the starting number of the range: 10
Enter the ending number of the range: 150
Palindrome numbers in the range 10 to 150 are:
11 22 33 44 55 66 77 88 99 101 111 121 131 141
Stepwise Explanation:
- Include Headers:
string.hforstrlenandstdlib.hforsprintf(though oftenstdio.hsuffices forsprintf). isPalindromeString(int n)Function:
- A character array
str[20]is declared to store the number as a string.20is chosen as a safe size for typical integer ranges. - Negative numbers are handled.
-
sprintf(str, "%d", n)converts the integerninto its string representation and stores it instr. -
strlen(str)determines the length of the string. - Two integer pointers,
i(starting from the beginning) andj(starting from the end), are used. - A
whileloop continues as long asiis less thanj. - Inside the loop,
str[i]is compared withstr[j]. If they are not equal, the string (and thus the number) is not a palindrome, and the function returns 0. - If they are equal,
iis incremented andjis decremented to move towards the center of the string. - If the loop completes without finding any mismatches, it means the string is a palindrome, and the function returns 1.
main()Function:
- Similar to the previous approach, it handles user input, range validation, and iterates through the numbers.
- It calls
isPalindromeString()for each number and prints it if it's a palindrome.
Conclusion
Finding palindrome numbers in a given range can be achieved through different algorithmic approaches in C. The mathematical digit reversal method is generally preferred for its efficiency and avoidance of string conversion overhead. The string conversion method, while slightly less efficient for large numbers, offers a clear and intuitive way to understand the palindrome check through character-by-character comparison. Both methods effectively solve the problem, allowing you to choose the one that best fits your requirements for performance or readability.
Summary
- Palindrome Definition: A number that reads the same forwards and backward.
- Problem: Identify all palindrome numbers within a user-specified numerical range.
- Mathematical Digit Reversal:
- Involves extracting digits using the modulo operator (
%). - Reconstructs a new number by reversing the order of the extracted digits.
- Compares the reversed number with the original.
- Generally more performant as it avoids string operations.
- String Conversion Method:
- Converts the integer to its string representation.
- Uses two pointers (one from the start, one from the end) to compare characters of the string.
- More intuitive for those familiar with string manipulation but can have a slight performance overhead.
- C Implementation: Both methods require a helper function to check for palindrome property and a
mainfunction to get the range and iterate through numbers, printing palindromes found.