Search This Blog

Loading...

Palindrome Program in C Source Code

C program for palindrome or palindrome in c programming: palindrome program in c language, c code to check if a string is a palindrome or not and for palindrome number. This program works as follows :- at first we copy the entered string into a new string, and then we reverse the new string and then compares it with original string. If both of them have same sequence of characters i.e. they are identical then the entered string is a palindrome otherwise not. To perform copy, reverse and compare operations we use strcpy, strrev and strcmp functions of string.h respectively, if you do not wish to use these functions see c programming code for palindrome without using string functions. Some palindrome strings examples are "dad", "radar", "madam" etc.

 
#include <stdio.h>

int is_palindrome(char*);
void copy_string(char*, char*);
void reverse_string(char*);
int string_length(char*);
int compare_string(char*, char*);

int main()
{
   char string[100];
   int result;

   printf("Enter a string\n");
   gets(string);

   result = is_palindrome(string);

   if ( result == 1 )
      printf("\"%s\" is a palindrome string.\n", string);
   else
      printf("\"%s\" is not a palindrome string.\n", string);

   return 0;
}

int is_palindrome(char *string)
{
   int check, length;
   char *reverse;

   length = string_length(string);  
   reverse = (char*)malloc(length+1);  

   copy_string(reverse, string);
   reverse_string(reverse);

   check = compare_string(string, reverse);

   free(reverse);

   if ( check == 0 )
      return 1;
   else
      return 0;
}

int string_length(char *string)
{
   int length = 0;

   while(*string)
   {
      length++;
      string++;
   }

   return length;
}

void copy_string(char *target, char *source)
{
   while(*source)
   {
      *target = *source;
      source++;
      target++;
   }
   *target = '\0';
}

void reverse_string(char *string)
{
   int length, c;
   char *begin, *end, temp;

   length = string_length(string);

   begin = string;
   end = string;

   for ( c = 0 ; c < ( length - 1 ) ; c++ )
       end++;

   for ( c = 0 ; c < length/2 ; c++ )
   {      
      temp = *end;
      *end = *begin;
      *begin = temp;

      begin++;
      end--;
   }
}

int compare_string(char *first, char *second)
{
   while(*first==*second)
   {
      if ( *first == '\0' || *second == '\0' )
         break;

      first++;
      second++;
   }
   if( *first == '\0' && *second == '\0' )
      return 0;
   else
      return -1;
}

No comments:

Post a Comment