View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Mastering Palindrome Program in C: Techniques and Code Examples

Updated on 14/04/20256,793 Views

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

What is a Palindrome Program in C?

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]

Why Write a Palindrome Program in C? 

You might be thinking, “Why bother writing a palindrome checker?” Great question! Here’s why it’s more than just a fun exercise:

  • It helps you understand data types: Working with both strings and integers lets you practice type conversions, string manipulation, and more.
  • It sharpens your loop skills: You'll likely use `for` or `while` loops to compare characters or digits from both ends toward the center.
  • It teaches conditionals: You’ll write logic to compare values step by step—perfect for grasping `if-else` statements.
  • You learn how to reverse things: Reversing a string or a number is a skill that shows up in a ton of real-world problems (e.g., data parsing, algorithms, even cryptography).
  • It boosts your logical thinking: At its core, palindrome checking is about thinking algorithmically—breaking down a problem into manageable parts. 

Also Explore: What are Data Structures in C & How to Use Them?

Different Methods to Implement Palindrome Program in C 

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. 

Method 1: Checking Palindrome Program in C for Numbers Using Function

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.

Key Concepts Used:

Code: Checking Palindrome Program in C Using Function 

#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);
}

Output

Enter an integer: 1331
1331 is a palindrome.

Enter an integer: 9876
9876 is not a palindrome.

Step-by-Step Explanation

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

  • The function stores the original number for comparison.
  • It then reverses the number using a `while` loop:
  • Extracts the last digit using `num % 10`.
  • Append this digit to the `reversed` number.
  • Removes the last digit from the original number using `num /= 10`.

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

  • The user inputs a number.
  • The program calls `isPalindrome(number)` to determine the result.
  • Based on the return value, it prints whether the number is a palindrome.

Check out the Executive Diploma in Data Science & AI with IIIT-B!

Method 2: Palindrome Check for Strings Using Library Functions

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.

Key Concepts Used:

Code: Checking Palindrome in C Using Library Functions

#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;
}

Sample Output

Enter a string: radar
The string is a palindrome.

Enter a string: hello
The string is not a palindrome.

Step-by-Step Explanation

1. Input Handling

  • The user inputs a string.
  • We use `gets()` to read the string. (Note: `gets()` is considered unsafe due to potential buffer overflows—use `fgets()` in modern code.) 

2. Copy and Reverse  

  • `strcpy(rev, str)` copies the original string into another character array so we can reverse it without altering the original.
  • `strrev(rev)` reverses the copied string in place. This function is available in some compilers like Turbo C, but not part of the C standard.

3. Comparison

  • `strcmp()` compares the original and reversed strings.
  • If both are equal, the string is a palindrome.

Method 3: Palindrome Check for Strings Using Recursion

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 

Key Concepts Used:

  • Recursion
  • Character arrays
  • Base and recursive cases

Code: Checking Palindrome Program in C Using Recursion

#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);
}

Sample Output

Enter a string: madam
The string is a palindrome.

Enter a string: world
The string is not a palindrome.

Step-by-Step Explanation

1. Input and Setup

  • The user inputs a string using `scanf()`. This reads a word (no spaces).
  • We calculate the length of the string using `strlen()`.

2. Calling the Recursive Function

  • `isPalindromeRecursive()` takes three arguments: the string, the starting index (`0`), and the ending index (`length - 1`).
  • It compares characters from the outside in (first and last, second and second-last, and so on).

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`).

Method 4: Palindrome Check for Strings Using a `for` Loop

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.

Key Concepts Used:

Code: Checking Palindrome Program in C Using `for` Loop

#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;
}

Sample Output

Enter a string: level
The string is a palindrome.

Enter a string: openai
The string is not a palindrome.

Step-by-Step Explanation

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

  • The loop runs from index `0` to `length/2`.
  • On each iteration, it compares the character at index `i` with the character at the corresponding end index: `length - i - 1`.

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.

Method 5: Checking Palindrome in C for Strings Using a `while` Loop

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.

Key Concepts Used:

  • Character arrays
  • `while` loop for index-based comparison
  • `strlen()` to determine the string length 

Code: Palindrome Check Using `while` Loop 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;
            break;
        }
        start++;
        end--;
    }

    if (isPalindrome) {
        printf("The string is a palindrome.\n");
    } else {
        printf("The string is not a palindrome.\n");
    }

    return 0;
}

Sample Output

Enter a string: racecar
The string is a palindrome.


Enter a string: hello
The string is not a palindrome.

Step-by-Step Explanation

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

  • The loop continues as long as `start` is less than `end`.
  • Inside the loop, we compare characters at `str[start]` and `str[end]`.
  • If any pair of characters do not match, we set `isPalindrome` to `0` and break out of the 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.

Method 6: Checking Palindrome in C for Strings Using Two References

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.

Key Concepts Used:

  • Two references (or pointers in C)
  • Character arrays
  • Comparison of characters from both ends 

Also explore and learn: Dangling pointer in C  

Code: Palindrome Check Using Two References 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;
}

Sample Output

Enter a string: madam
The string is a palindrome.

Enter a string: example
The string is not a palindrome.

Step-by-Step Explanation

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  

  • After the loop completes, we check the `isPalindrome` flag:
  • If it's `1`, the string is a palindrome.
  • If it's `0`, the string is not a palindrome.

Complexity Analysis of Differnet Palindrome Program in C

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. 

Key Insights:

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.

Conclusion 

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.

FAQs 

1. Can palindrome checking be done for numbers in C?  

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.

2. How do you handle an empty string when checking for a palindrome?  

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.

3. Can we check for palindromes in C using pointers?  

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.

4. What should we do if the input string contains mixed case characters?  

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.

5. What if the string contains non-alphanumeric characters like punctuation or spaces?  

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.

6. How would you check a palindrome with whitespace and punctuation?  

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.

7. Can the palindrome check be done for a sentence or phrase?  

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.

8. Is there a way to optimize palindrome checking for very long strings?  

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.

9. Can the palindrome check be case-sensitive?  

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.

10. What happens if the string has odd or even length?  

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.

11. Can palindrome checking be done for large data types, like big integers?  

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. 

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.