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

C Program to Check for Palindrome String

Last Updated : 18 Apr, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
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 :

  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++
#include <iostream>
#include <string>

using namespace std;

bool isPalindrome(string str) {
    int low = 0;
    int high = str.size() - 1;

    // Keep comparing characters while they are same
    while (low < high) {
        if (str[low] != str[high]) {
            return false; // not a palindrome.
        }
        low++; // move the low index forward
        high--; // move the high index backwards
    }
      return true; // is a palindrome     
}

int main()
{
    string str= "abbba";
    string str1 = "abcded";
    
    cout << str << " is palindrome " << isPalindrome(str) << endl;
    cout << str1 << " is palindrome " << isPalindrome(str1) <<endl;
    return 0;
}
C
#include <stdio.h>
#include <string.h>

int isPalindrome(char str[]) {
    int low = 0;
    int high = strlen(str) - 1;

    // Keep comparing characters while they are same
    while (low < high) {
        if (str[low] != str[high]) {
            return 0; // not a palindrome.
        }
        low++; // move the low index forward
        high--; // move the high index backwards
    }
    return 1; // is a palindrome
}

int main() {
    char str[] = "abbba";
    char str1[] = "abcded";
    
    printf("%s is palindrome %d\n", str, isPalindrome(str));
    printf("%s is palindrome %d\n", str1, isPalindrome(str1));
    
    return 0;
}
Java
public class Main {
    // Function to check if a string is a palindrome
    static boolean isPalindrome(String str) {
        int low = 0;
        int high = str.length() - 1;

        // Keep comparing characters while they are same
        while (low < high) {
            if (str.charAt(low) != str.charAt(high)) {
                return false; // not a palindrome.
            }
            low++; // move the low index forward
            high--; // move the high index backwards
        }
        return true; // is a palindrome
    }

    public static void main(String[] args) {
        String str = "abbba";
        String str1 = "abcded";

        System.out.println(str + " is palindrome " + isPalindrome(str));
        System.out.println(str1 + " is palindrome " + isPalindrome(str1));
    }
}

Output
abbba is palindrome 1
abcded is palindrome 0

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


Algorithm 2 : (Recursive Approach)

The approach remains the same. Recursively check if it’s a palindrome or not.
Below is the code for better understanding.

C
// C implementation to check if a given
// string is palindrome or not
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isPalindrome(char str[], int l, int h)
{
    // if the string size is 0 or 1
    // it is a palindrome
    if (l >= h)
        return true;

    // if both the terminal characters
    // not matching, not palindrome
    if (str[l] != str[h])
        return false;

    // call the smaller sub-problem
    return isPalindrome(str, l + 1, h - 1);
}

int main()
{
    char str[] = { "abbba" };

    // Start from first and
    // last character of str
    int l = 0;
    int h = strlen(str) - 1;

    bool ans = isPalindrome(str, l, h);
    if (ans) {
        printf("%s is a palindrome\n", str);
    }
    else {
        printf("%s is not a palindrome\n", str);
    }

    return 0;
}

Output
abbba is a palindrome

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




Previous Article
Next Article

Similar Reads

Count all palindrome which is square of a palindrome
Given two positive integers L and R (represented as strings) where [Tex]1\leq L \leq R\leq10^{18} [/Tex]. The task is to find the total number of super-palindromes in the inclusive range [L, R]. A palindrome is called super-palindrome if it is a palindrome and also square of a palindrome. Examples: Input: L = "4", R = "1000" Output: 4 Explanation:
10 min read
Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)
Write a program to check if a sentence is a palindrome or not. You can ignore white spaces and other characters to consider sentences as a palindrome. Examples: Input : str = "Too hot to hoot." Output : Sentence is palindrome. Input : str = "Abc def ghi jklm." Output : Sentence is not palindrome. Note: There may be multiple spaces and/or dots betwe
12 min read
Check if String formed by first and last X characters of a String is a Palindrome
Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false. Examples: Input: str = abcdefba, X = 2Output: trueExplanation: First 2 characters of both string str and reversed string str are same. Input: str =
5 min read
Check if given Binary String can be made Palindrome using K flips
Given a binary string str, the task is to determine if string str can be converted into a palindrome in K moves. In one move any one bit can be flipped i.e. 0 to 1 or 1 to 0. Examples: Input: str = "101100", K = 1Output: YESExplanation: Flip last bit of str from 0 to 1. Input: str = "0101101", K = 2Output: NOExplanation: Three moves required to mak
5 min read
Check if a string can be rearranged to form special palindrome
Given a string str, the task is to check if it can be rearranged to get a special palindromic string. If we can make it print YES else print NO. A string is called special Palindrome that contains an uppercase and a lower case character of the same character in the palindrome position. Example: ABCcba is a special palindrome but ABCCBA is not a spe
8 min read
Check if there exists any sub-sequence in a string which is not palindrome
Given a string of lowercase English alphabets. The task is to check if there exists any subsequence in the string which is not a palindrome. If there is at least 1 subsequence that is not a palindrome then print YES, otherwise print NO. Examples: Input : str = "abaab"Output: YESSubsequences "ab" or "abaa" or "aab", are not a palindrome.Input : str
8 min read
Check if string can be rearranged so that every Odd length Substring is Palindrome
Given a string S. The task is to check whether it is possible to rearrange the string such that every substring of odd length is a palindrome. Examples: Input: S = "oiooi" Output: YES The string can be rearranged as "oioio" Input: S = "yuyuo" Output: NO Approach: The very first observation is if all the characters of the string are the same then ev
7 min read
Check if string remains palindrome after removing given number of characters
Given a palindromic string str and an integer N. The task is to find if it is possible to remove exactly N characters from the given string such that the string remains a palindrome. Examples: Input: str = "abba", N = 1 Output: Yes Remove 'b' and the remaining string "aba" is still a palindrome. Input: str = "aba", N = 1 Output: Yes Approach: It ca
3 min read
Check if string is palindrome after removing all consecutive duplicates
Given a string str, the task is to remove all the consecutive duplicates from the string str and check if the final string is palindrome or not. Print "Yes" if it is a palindromic else print "No". Examples: Input: str = "abbcbbbaaa" Output: Yes Explanation: On removing all consecutive duplicates characters, the string becomes "abcba" which is a pal
7 min read
Check given string is oddly palindrome or not | Set 2
Given string str, the task is to check if characters at the odd indexes of str form a palindrome string or not. If not then print "No" else print "Yes". Examples: Input: str = "osafdfgsg", N = 9 Output: Yes Explanation: Odd indexed characters are = { s, f, f, s } so it will make palindromic string, "sffs". Input: str = "addwfefwkll", N = 11 Output:
12 min read
three90RightbarBannerImg