For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
The Palindrome program in C is not only interesting but also a common problem in programming. If you're new to working with C, knowing how to check for palindromes can be a useful skill. It’s so crucial that top-rated software development courses must include this topic. And in this blog, we’ll dive into how to implement a palindrome program in C, breaking down various methods to solve this problem.
We’ll explore different approaches, including using loops, recursion, and even library functions. Each method will be explained with code examples and a clear, step-by-step guide to help you understand how it works. Whether you’re just starting with C or looking to improve your skills, this blog will walk you through everything you need to know to confidently implement palindrome checks in your programs.
Must Explore: Introduction to C Tutorial
Let’s dive into it—what’s this “palindrome” thing all about, and why does it matter in C programming?
A palindrome is a sequence that reads the same backward as it does forward. It could be a word like "level", a number like 12321, or even a phrase (if you ignore spaces and punctuation) like "A man, a plan, a canal, Panama". Pretty neat, right?
Now, when we talk about a Palindrome Program in C, we’re referring to a small program written in the C language that checks whether a given input, usually a string or a number is a palindrome or not. The logic behind it may sound simple, but it’s a brilliant way to understand the core programming concepts that form the foundation of more advanced problem-solving later on.
Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]
You might be thinking, “Why bother writing a palindrome checker?” Great question! Here’s why it’s more than just a fun exercise:
Also Explore: What are Data Structures in C & How to Use Them?
In this section, we’ll understand the top six methods to implement a palindrome program in C. You can use any of the methods, as per your software requirements.
This method uses a modular approach to check if a number is a palindrome by defining a separate function. Structuring code this way makes it more readable, reusable, and easier to maintain—especially as your projects grow.
#include <stdio.h>
// Function declaration
int isPalindrome(int num);
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
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
int isPalindrome(int num) {
int reversed = 0, remainder, original;
original = num;
while (num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num /= 10;
}
return (original == reversed);
}
Enter an integer: 1331
1331 is a palindrome.
Enter an integer: 9876
9876 is not a palindrome.
1. Function Declaration and Usage
A separate function `isPalindrome(int num)` is defined to encapsulate the logic for checking if a number is a palindrome. This helps maintain clean separation between logic and input/output operations.
2. Reversing the Number
3. Comparison and Return Value
After the reversal, the function checks if the reversed number matches the original. If they’re equal, the function returns `1` (true); otherwise, it returns `0` (false).
4. Main Function Flow
Check out the Executive Diploma in Data Science & AI with IIIT-B!
In this method, we use the C Standard Library's string handling functions—like `strlen()` and `strcmp()`—to simplify our logic. Instead of manually comparing characters or writing a loop to reverse the string ourselves, we leverage built-in tools to streamline the process.
This method is especially useful when working with string-based palindromes such as names, words, or phrases.
#include <stdio.h>
#include <string.h>
int main() {
char str[100], rev[100];
printf("Enter a string: ");
gets(str); // Note: unsafe; consider using fgets() in modern code
strcpy(rev, str); // Copy original string into rev
strrev(rev); // Reverse the copied string
if (strcmp(str, rev) == 0) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
Enter a string: radar
The string is a palindrome.
Enter a string: hello
The string is not a palindrome.
1. Input Handling
2. Copy and Reverse
3. Comparison
Recursion is a powerful concept in programming where a function calls itself to solve smaller instances of the same problem. In this method, we use recursion to check if a string is a palindrome by comparing the first and last characters and recursively checking the substring in between.
This approach not only helps you write elegant code but also deepens your understanding of how function calls work in memory.
Also pursue the most advanced Machine Learning Course
#include <stdio.h>
#include <string.h>
// Function declaration
int isPalindromeRecursive(char str[], int start, int end);
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str); // Note: Reads input until space
int len = strlen(str);
if (isPalindromeRecursive(str, 0, len - 1)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
// Recursive function to check for palindrome
int isPalindromeRecursive(char str[], int start, int end) {
// Base case: if start >= end, it's a palindrome
if (start >= end)
return 1;
// If characters don't match, it's not a palindrome
if (str[start] != str[end])
return 0;
// Recursive case: move inward
return isPalindromeRecursive(str, start + 1, end - 1);
}
Enter a string: madam
The string is a palindrome.
Enter a string: world
The string is not a palindrome.
1. Input and Setup
2. Calling the Recursive Function
3. Base Case
If `start >= end`, we’ve checked all matching pairs—so the string is a palindrome.
4. Mismatch Check
If characters at the current indices don’t match, the function returns `0` immediately.
5. Recursive Call
If characters match, the function calls itself again with the next inner indices (`start + 1`, `end - 1`).
This method uses a basic `for` loop to check if a string is a palindrome by comparing characters from the beginning and end of the string, moving inward one step at a time.
It’s one of the most commonly taught methods because it’s easy to understand, doesn’t require extra memory (no reversed copy of the string), and doesn’t depend on recursion or compiler-specific functions.
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, length, isPalindrome = 1;
printf("Enter a string: ");
scanf("%s", str); // Reads until whitespace
length = strlen(str);
for (i = 0; i < length / 2; i++) {
if (str[i] != str[length - i - 1]) {
isPalindrome = 0;
break;
}
}
if (isPalindrome) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
Enter a string: level
The string is a palindrome.
Enter a string: openai
The string is not a palindrome.
1. Input Handling
The user inputs a word using `scanf()`. It will read characters until a space is encountered.
2. Calculate Length
We use `strlen()` to get the length of the input string.
3. Compare Characters Using a `for` Loop
4. Early Exit on Mismatch
If any pair doesn’t match, we set `isPalindrome` to `0` and exit the loop early using `break`.
5. Result Output
After the loop, we check the flag `isPalindrome` to print whether the string is a palindrome or not.
In this method, we employ a `while` loop to check if a string is a palindrome by comparing characters from the outermost ends and progressively moving inward. The `while` loop is often used in situations where you don’t know in advance how many iterations are needed, making it another great approach for palindrome checking.
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int start, end, isPalindrome = 1;
printf("Enter a string: ");
scanf("%s", str); // Reads until whitespace
start = 0;
end = strlen(str) - 1;
while (start < end) {
if (str[start] != str[end]) {
isPalindrome = 0;
break;
}
start++;
end--;
}
if (isPalindrome) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
Enter a string: racecar
The string is a palindrome.
Enter a string: hello
The string is not a palindrome.
1. Input Handling
The user inputs a string using `scanf()`. It stops at the first space and reads the string.
2. Initialize `start` and `end`
We initialize two indices: `start` at the beginning of the string (`0`) and `end` at the last character (`strlen(str) - 1`).
3. Comparing Characters Using `while` Loop
4. Move Inward
If the characters match, we increment `start` and decrement `end` to move toward the center of the string.
5. Result Output
After the loop completes, if `isPalindrome` remains `1`, the string is a palindrome. Otherwise, it’s not.
In this method, we use two references (or pointers) to check if a string is a palindrome. One pointer starts from the beginning (`start`), and the other starts from the end (`end`). Both pointers move toward the center of the string, comparing characters at each position. If all characters match, the string is a palindrome.
Also explore and learn: Dangling pointer in C
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int start, end, isPalindrome = 1;
printf("Enter a string: ");
scanf("%s", str); // Reads until whitespace
start = 0;
end = strlen(str) - 1;
while (start < end) {
if (str[start] != str[end]) {
isPalindrome = 0; // Set flag if characters don't match
break;
}
start++; // Move the start pointer to the right
end--; // Move the end pointer to the left
}
if (isPalindrome) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
Enter a string: madam
The string is a palindrome.
Enter a string: example
The string is not a palindrome.
1. Input Handling
The user inputs a string using `scanf()`, and we read it until the first whitespace.
2. Initialize `start` and `end` References
We set `start` to point to the beginning of the string (`0`), and `end` to point to the last character (`strlen(str) - 1`).
3. Comparison Using Two References
The `while` loop runs as long as `start` is less than `end`.
Inside the loop, we compare the characters at positions `start` and `end`. If they are not equal, we set `isPalindrome` to `0` and break out of the loop.
4. Move References Inward
If the characters match, we increment the `start` reference and decrement the `end` reference to move toward the center of the string.
5. Result Output
Now, we’ll learn about the time and space complexity of all the methods that we used to implement palindrome program in C.
Method | Time Complexity | Space Complexity | Explanation |
Using Functions | O(n) | O(1) | - The time complexity is O(n) because we loop through the digits of the number once to reverse it and compare. - Space complexity is O(1) as we only use a few variables. |
Using Library Functions | O(n) | O(n) | - Time complexity is O(n) due to the reversal of the string using strrev(), and comparing it to the original string using strcmp(). - Space complexity is O(n) because of the extra space for the reversed string. |
Using Recursion | O(n) | O(n) | - Time complexity is O(n) since each recursive call processes one character at a time until the base case is reached. - Space complexity is O(n) due to the recursive call stack. |
Using for Loop | O(n) | O(1) | - Time complexity is O(n/2), which simplifies to O(n) because we only need to loop through half the string. - Space complexity is O(1) because no extra space is used apart from a few variables. |
Using while Loop | O(n) | O(1) | - Time complexity is O(n/2), which simplifies to O(n), since the loop iterates half the string length. - Space complexity is O(1) because we only use a couple of variables. |
Using Two References | O(n) | O(1) | - Time complexity is O(n/2), which simplifies to O(n), as we compare from both ends of the string. - Space complexity is O(1) as no additional memory is needed beyond the string itself. |
1. Time Complexity:
All methods have a time complexity of O(n), where `n` is the length of the string or the number of digits in the number (in the case of the numeric palindrome check). This is because each method processes each element of the input at least once.
2. Space Complexity:
Most methods have O(1) space complexity, which means they don’t require additional space proportional to the input size, apart from a few variables.
The exception is Method 2 (Library Functions), which has O(n) space complexity due to the need to create a reversed string, and Method 3 (Recursion), which has O(n) space complexity due to the recursive call stack.
In conclusion, we’ve explored multiple ways to check for palindromes in C, each with its pros and cons. Using functions is simple and works well for numeric palindromes, while library functions make string checks quick but require extra memory.
Additionally, recursion provides a clean approach but can use more memory due to the call stack. Loop-based methods (`for` and `while`) are efficient and memory-friendly, while the two-reference method offers an intuitive way to compare characters from both ends. The right method depends on your needs, balancing simplicity, memory use, and performance.
Yes, palindrome checking can be applied to numbers by converting them to a string or by reversing the digits of the number and comparing the reversed version with the original number.
An empty string is considered a palindrome by definition because it reads the same forwards and backwards, so you can treat it as a valid palindrome.
Yes, you can use pointers to traverse the string from both ends. By incrementing a pointer from the beginning and decrementing one from the end, you can compare characters to check if they are the same.
To handle mixed case characters, you can convert the entire string to either lowercase or uppercase using C's `tolower()` or `toupper()` functions before performing the palindrome check.
If the string contains spaces or punctuation, you can preprocess the string to remove non-alphanumeric characters before performing the palindrome check. You can use functions like `isalnum()` to filter out unwanted characters.
You can first preprocess the string by removing all spaces, punctuation, and converting it to lowercase. After cleaning the string, you can proceed with any of the palindrome checking methods discussed.
Yes, if you're checking a phrase, you should first remove any spaces and punctuation, then check if the remaining alphanumeric characters form a palindrome.
For very large strings, methods using two pointers or references are highly efficient. They provide O(n) time complexity while only requiring a constant amount of space, making them optimal for long strings.
Yes, a case-sensitive palindrome check means you treat uppercase and lowercase letters as different characters. In this case, no additional conversion to lowercase or uppercase would be necessary.
Both odd and even-length strings can be palindromes. For odd-length strings, the middle character doesn't affect the palindrome check since it’s already in the center. The methods we've discussed will work for both even and odd-length strings.
Yes, for large integers, you can first convert the number into a string, and then apply the palindrome checking logic. Alternatively, you can reverse the digits of the number mathematically without converting to a string.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.