C Program to Check Palindrome

Palindrome in C: A string or number is palindrome if it same whether we read it forward or backward. This program checks whether a string is palindrome or not.

Algorithm or Solution:

Here is the algorithm or logical solution of C program to check if given string is palindrome
  1. Start
  2. Accept a string to check if it a palindrome or not.
  3. Define a function to check if the string is palindrome or not>.
  4. Declare another character array and store the reverse string of the given string.
  5. Using the standard library function strcmp() compare the original and reverse of original string that we stored in another character array.
  6. If they match (strcmp() function returns 0 when both strings are equal) return 1 else return 0.
  7. Use this function in main to check if given string is palindrome or not ? using if else statement.
  8. Stop.

Note: Instead of fgets() you can use gets() function. But it may cause buffer overflow.

C Program to check palindrome without using string functions:

Here is the source code of a C program to check if given string is palindrome
/* Aim: Write a c program to check if given string is palindrome*/

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

int Palindrome(char str[]); // Palindrome() Function Prototype

void main()
{
 char str[20]; 

 printf("\n Enter any string (Max 20 characters):- ");
 fgets(str,20,stdin);

 if(Palindrome(str)==1)
  printf("\n Given String is palindrome --%s \n",str);
 else
  printf("\n Given String is not palindrome --%s \n",str);
 
}

// Implicit Palindrome() function to check if given string is palindrome without using string library functions

int Palindrome(char str[])
{
 int i,j=0;
 char str1[20];

 for(i=strlen(str)-1;i>=0;i--)
 { 
 str1[j]=str[i];
 j++;
 } 

 str1[j]='\0';

 if(strcmp(str,str1)==0)
 {return 1;}
 else 
 {return 0;}
}

/* Output of above code / Runtime Cases:-

 Enter any string (Max 20 characters):- MrJoshi

 Given String is not palindrome --MrJoshi 

 Enter any string (Max 20 characters):- madam

 Given String is palindrome -- madam

*/
String Palindrome in Java