C Program to check if a string is a palindrome
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
- Input:
madam- Output: The string is a palindrome.
- Explanation: "madam" reads the same forwards and backwards.
- 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:
- Reverse the String: Generate a reverse of the original string.
- Compare Strings: Compare the original string with its reversed version.
- 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
-
Initialization of the
flagvariable:flag = 1;- Here,
flagis initialized to1. This variable acts as an indicator of whether the string is a palindrome or not. 1means we assume the string is a palindrome unless proven otherwise.0will indicate that the string is not a palindrome.
- Here,
-
While Loop:
while (left < right) {- This loop will continue to run as long as
leftindex is less thanrightindex. leftandrightare indices used to compare characters from the beginning and end of the string, respectively.
- This loop will continue to run as long as
-
Character Comparison:
if (str[left] != str[right]) { flag = 0; break; }- Inside the loop, it compares the characters at the
leftandrightindices. - If the characters at these positions are not equal (
str[left] != str[right]), it setsflagto0(indicating the string is not a palindrome) and breaks out of the loop. - The
breakstatement stops further execution of the loop as we have already determined that the string is not a palindrome.
- Inside the loop, it compares the characters at the
-
Increment and Decrement:
left++; right--;- If the characters at the
leftandrightindices are equal, theleftindex is incremented by1and therightindex is decremented by1. - This moves the indices towards the center of the string for the next comparison.
- If the characters at the
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
flagto0and 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
flagremains1).
Example Walk-through
Let's illustrate this with an example string "madam":
- Initialization:
str = "madam"left = 0right = 4(index of the last character)flag = 1
- First Iteration:
str[left]is'm'andstr[right]is'm'(both are equal)- Increment
leftto1 - Decrement
rightto3
- Second Iteration:
str[left]is'a'andstr[right]is'a'(both are equal)- Increment
leftto2 - Decrement
rightto2
- Third Iteration:
- Now,
leftis not less thanright(left == right), so the loop terminates. - Since
flagis still1, the string is confirmed to be a palindrome.
- Now,
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.