In this post we’re going to implement a C program to check A given string is a palindrome or not.
A string is said to be palindrome if reverse of the string is same as string.
For example, “abba” is palindrome, but “abbc” is not palindrome.
Steps to solve this problem
- Find the length of the string using the function len(str). Assume it as n.
- Initialize low and high as 0 and n-1 respectively.
- Check if str[low] and str[high] are same. if not return false
- increase low by 1 and decrease high by 1.
- Repeat step 3 and 4 until low>high.
- if we reach step 5 that means we’ve got all str[low] and str[high] same.
Below is the C implementation to check if a given string is palindrome or not.
#include <stdio.h>
#include <string.h>
// A function to check if a string str is palindrome
// Driver program to test above function
int main()
{
void isPalindrome(char str[])
{
// Start from leftmost and rightmost corners 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;
}
}
printf("%s is a palindrome\n", str);
}
isPalindrome("abba");
isPalindrome("abbccbba");
isPalindrome("geekycodes");
return 0;
}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
For more Programming related blogs Visit Us Geekycodes . Follow us on Instagram.
If you’re a college student and have skills in programming languages, Want to earn through blogging? Mail us at geekycomail@gmail.com