C Program to check if a string is a palindrome

Category: C Program
Tags: #cprogram#string

Learn how to check if a string is a palindrome in C with a simple and efficient algorithm. This article explains the logic, provides a step-by-step code implementation, and offers examples to illustrate the concept.

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backwards. Checking if a string is a palindrome is a common task in programming that helps understand string manipulation and algorithmic thinking.

In this article, we'll explore a C program that checks if a given simple string (without spaces, punctuation, or mixed case) is a palindrome. We'll discuss the logic behind the program and provide the code implementation.

Examples

  1. Input: madam
    • Output: The string is a palindrome.
    • Explanation: "madam" reads the same forwards and backwards.
  2. Input: hello
    • Output: The string is not a palindrome.
    • Explanation: "hello" does not read the same forwards and backwards.

Logic Behind the Program

To determine if a string is a palindrome:

  1. Reverse the String: Generate a reverse of the original string.
  2. Compare Strings: Compare the original string with its reversed version.
  3. Check for Palindromic Nature: If the strings match, the input is a palindrome; otherwise, it's not.

We will not actually reverse the string, but check if the string will remain the same after reversal or not by traversing.

Write a C Program to check if a string is a palindrome

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    int length, left, right, flag;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove newline character if present
    str[strcspn(str, "\\n")] = '\\0';

    length = strlen(str);
    left = 0;
    right = length - 1;

    // Check for palindrome
    flag = 1;
    while (left < right) {
        if (str[left] != str[right]) {
            flag = 0;
            break;
        }
        left++;
        right--;
    }

    if (flag) {
        printf("%s is a palindrome.", str);
    } else {
        printf("%s is not a palindrome.", str);
    }

    return 0;
}

Output

Enter a string: madam
madam is a palindrome.

Explanation of the Code

Certainly! Let's break down the provided code snippet that checks if a string is a palindrome:

flag = 1;
while (left < right) {
    if (str[left] != str[right]) {
        flag = 0;
        break;
    }
    left++;
    right--;
}

Explanation

  1. Initialization of the flag variable:

    flag = 1;
    
    • Here, flag is initialized to 1. This variable acts as an indicator of whether the string is a palindrome or not.
    • 1 means we assume the string is a palindrome unless proven otherwise.
    • 0 will indicate that the string is not a palindrome.
  2. While Loop:

    while (left < right) {
    
    • This loop will continue to run as long as left index is less than right index.
    • left and right are indices used to compare characters from the beginning and end of the string, respectively.
  3. Character Comparison:

    if (str[left] != str[right]) {
        flag = 0;
        break;
    }
    
    • Inside the loop, it compares the characters at the left and right indices.
    • If the characters at these positions are not equal (str[left] != str[right]), it sets flag to 0 (indicating the string is not a palindrome) and breaks out of the loop.
    • The break statement stops further execution of the loop as we have already determined that the string is not a palindrome.
  4. Increment and Decrement:

    left++;
    right--;
    
    • If the characters at the left and right indices are equal, the left index is incremented by 1 and the right index is decremented by 1.
    • This moves the indices towards the center of the string for the next comparison.

Summary

  • The code starts by assuming the string is a palindrome (flag = 1).
  • It then compares characters from the outermost edges towards the center.
  • If any pair of characters doesn't match, it sets flag to 0 and exits the loop, indicating that the string is not a palindrome.
  • If the loop completes without finding any mismatched characters, the string is confirmed to be a palindrome (as flag remains 1).

Example Walk-through

Let's illustrate this with an example string "madam":

  1. Initialization:
    • str = "madam"
    • left = 0
    • right = 4 (index of the last character)
    • flag = 1
  2. First Iteration:
    • str[left] is 'm' and str[right] is 'm' (both are equal)
    • Increment left to 1
    • Decrement right to 3
  3. Second Iteration:
    • str[left] is 'a' and str[right] is 'a' (both are equal)
    • Increment left to 2
    • Decrement right to 2
  4. Third Iteration:
    • Now, left is not less than right (left == right), so the loop terminates.
    • Since flag is still 1, the string is confirmed to be a palindrome.

This simple but effective algorithm ensures that we can determine if a string is a palindrome by comparing characters from both ends towards the centre, stopping as soon as we find a mismatch.


Recommended Posts