Write a C program for palindrome test. A palindrome is a sequence of word,phrase or number which is same when you read either from forward direction or from backward direction.For examples string “DAD” is palindrome because “DAD” – Reads “DAD” from either side, so, it is Palindrome.
Here is the steps to check palindrome>

  • Store the input string
  • Reverse the input string,and store in temporary string.
  • Compare the input string with the temporary string.
  • If both the strings are same then the input string is palindrome.

Sample code to check palindrome:

 

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

char *rev(char *str);
int main() {
	char *inp_str = "dad";
	char *tmp = (char *) malloc(strlen(inp_str));
	strcpy(tmp, inp_str);
	tmp = rev(tmp);

	// printf("tmp is now %s\n",tmp);
	if (strcmp(inp_str, tmp) == 0)
		printf("input string is a palindrome.\n");
	else
		printf("input string is not a palindrome.\n");
	return 0;
}

char *
rev(char *str) {
	char *p1, *p2;
	if (!str || !*str)
		return str;
	for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) {
		*p1 ^= *p2;
		*p2 ^= *p1;
		*p1 ^= *p2;
	}
	return str;

}

 



Related Contents to follow