The Wayback Machine - https://web.archive.org/web/20240118174820/https://www.geeksforgeeks.org/c-program-check-given-string-palindrome/
Open In App
Related Articles

C Program to Check for Palindrome String

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

A string is said to be palindrome if the reverse of the string is the same as the string. For example, “abba” is a palindrome because the reverse of “abba” will be equal to “abba” so both of these strings are equal and are said to be a palindrome, but “abbc” is not a palindrome.

In this article, we will see a simple program to check whether the string is palindrome or not.

Recommended Practice

Algorithm

  1. Initialize 2 variables, l from the start and h from the end of the given string.
  2. Now, we will compare the characters at index l and h with each other
  3. If the characters are not equal, the string is not palindrome.
  4. If the characters are equal, we will increment l and decrement h.
  5. Steps 2,3 and 4 will be repeated till ( l < h ) or we find unequal characters.
  6. If we reach the condition ( l < h ), it means all the corresponding characters are equal and the string is palindrome.

Basically, we traverse the string in forward and backward directions comparing characters at the same distance from start and end. If we find a pair of distinct characters, the string is not palindrome. If we reach the midpoint, the string is palindrome.

Palindrome String Program in C

C




// C implementation to check if a given
// string is palindrome or not
#include <stdio.h>
#include <string.h>
 
int main()
{
    char str[] = { "abbba" };
 
    // Start from first and
    // last character of str
    int l = 0;
    int h = strlen(str) - 1;
 
    // Keep comparing characters
    // while they are same
    while (h > l) {
        if (str[l++] != str[h--]) {
            printf("%s is not a palindrome\n", str);
            return 0;
            // will return from here
        }
    }
 
    printf("%s is a palindrome\n", str);
 
    return 0;
}


Output

abbba is a palindrome




Complexity Analysis

Time complexity: O(n), where n is the number of characters in the string.
Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 26 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials