This C program checks a given string whether it is a palindrome or not. The string is read from left to right and right to left and each character is matched. If all the characters in the input string match correctly, then it is a palindrome string, otherwise not.
This program is written using Dev C++ compiler version 4.9.9.2 on a Windows 7 64-bit system. You may use any ANSI C compiler and compile this program. The goal is to get an error-free program.
Before you get started with the program, we recommend you to learn the following C programming concepts for the better understanding of this example.
- C Printing Outputs
- C Reading Input Values
- C Arithmetic Operators
- C Logical Operators
- C Flow Control Structures
- C For Loop
Problem Definition
A palindrome string is a special string which is same when you read it from left-to-right or right-to-left.
For example, the string “ToboT“, is same if you read it from left-to-right or right-to-left, therefore, it is a Palindrome.
When the program is executed, provide an input string to read and it will check whether it is a palindrome string or not and display the output to the console.
How does the program process the input string?
Each of the step helps in isolating the character of the input string and compare it from both direction. It should match in order to be a palindrome.
Step 1 – Read the input string
Step 2 – Read the input string from left-to-right & right-to-left character by character.
Step 3 – Compare each character of left side to the right side character one at a time.
Step 4 – If any character is different, set flag = 1, else flag = 0.
Step 5 – If flag = = 0, print “It is a Palindrome“.
Step 6 – Finally, if flag = = 1, print” It is not a Palindrome“.
Step 7 – End the program.
Flowchart – Check a Palindrome String
Program Code – Palindrome String
/*Program to Check if the String is Palindrome or not */
#include <stdio.h>
#include <conio.h>
main()
{
char string [80],c;
int i,j,len,flag=0;
/* Read the string */
printf("Enter a String for Palindrome Check:\n\n");
scanf("%[^n]",string);
printf("%s",string);
/* Find length of the string */
for(len=0;string[len]!='\0';len++)
printf("\n\nLength is %d\n",len);
/* Double initialisation for FOR loop */
for(i=0,j=len-1;i<len/2;i++,j--)
{
if(string[i]!=string[j])
flag=1;
}
/* Check if Palindrome and print the result */
if(flag)
{
for(i=1;i<=30;i++)
printf("_");printf("\n\n");
printf("\nString is not Palindrome.\n");
for(i=1;i<=30;i++)
printf("_");printf("\n\n");
}
else
{
for(i=1;i<=30;i++)
printf("_");printf("\n\n");
printf("\nString is a Palindrome.\n");
for(i=1;i<=30;i++)
printf("_");printf("\n\n");
}
system("PAUSE");
return 0;
}
Output
The output of the program is given below. The program reads a string called “TaboT” and prints the output to the console.
Enter a String for Palindrome Check:
tabot
tabot
Length is 5
_____________________________
String is not Palindrome.
_____________________________