codescracker


c

C Program to Check String is Palindrome or Not



« C Tutorial C Examples »

Check String is Palindrome or Not in C

The question is, write a program in C to enter any string at run-time and check whether it is palindrome or not.

Those string whose all the opposite characters are same is palindrome. And if any of the opposite character mismatched, then the string is not palindrome. For example, codoc is palindrome, codssdoc is palindrome, codes is not palindrome, codescracker is not palindrome.

C Programming Code to Check String is Palindrome or Not

The C program given below asks from the user to enter string at run-time, and checks whether it is a palindrome or not, to display the message at output screen accordingly.

// Write a program in C to input in string
// and check whether it is palindrome or not

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
	char str[50];
	int i, j, len, chk=0;
	printf("Enter any string (word): ");
	scanf("%s", str);
	len = strlen(str);
	for(i=0, j=(len-1); i<=(len-1); i++, j--)
	{
		if(str[i] != str[j])
		{
			chk=1;
			break;
		}
	}
	if(chk==1)
	{
		printf("The string is Not Palindrome.");
	}
	else
	{
		printf("The string is Palindrome.");
	}
	getch();
	return 0;
}

The above program is written under CodeBlocks IDE and therefore here is the output after build and run. This is the first screenshot of first sample run:

c program check palindrome string

And here is the second screenshot of first sample run:

c program string palindrome or not

As the reverse of codescracker is rekcarcsedoc which is not equal to the original string, that is codescracker, therefore the string is not palindrome.

Here is the first screenshot of second sample run:

check string palindrome c program

Here in this case, the reverse of codoc is codoc which is same as the original string, that is codoc, therefore the string is palindrome.

Main Steps Involved in above Program

Here are the steps involved in above program:

Here is another sample run for palindrome string:

check palindrome string c program

And here is one more sample run for not palindrome string:

palindrome string c program

« C Tutorial C Examples »






Tools
Calculator

Quick Links
Signup - Login - Give Online Test