Saturday, February 9, 2013

Palindrome number in c

c palindrome program, c program for palindrome

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.

 

Palindrome number in c

#include <stdio.h>
 
main()
{
   int n, reverse = 0, temp;
 
   printf("Enter a number to check if it is a palindrome or not\n");
   scanf("%d",&n);
 
   temp = n;
 
   while( temp != 0 )
   {
      reverse = reverse * 10;
      reverse = reverse + temp%10;
      temp = temp/10;
   }
 
   if ( n == reverse )
      printf("%d is a palindrome number.\n", n);
   else
      printf("%d is not a palindrome number.\n", n);
 
   return 0;
}

C program for palindrome without using string functions

#include <stdio.h>
#include <string.h>
 
int main()
{
   char text[100];
   int begin, middle, end, length = 0;
 
   gets(text);
 
   while ( text[length] != '\0' )
      length++;
 
   end = length - 1;
   middle = length/2;
 
   for( begin = 0 ; begin < middle ; begin++ )
   {
      if ( text[begin] != text[end] )
      {
         printf("Not a palindrome.\n");
         break;
      }
      end--;
   }
   if( begin == middle )
      printf("Palindrome.\n");
 
   return 0;
}

No comments:

Post a Comment