Thursday 28 March 2013

Palindrome

Palindrome number is a number that reads same from backward and forward. For example 101 is palindrome because when we reverse its digit we get 101. And 123 is not a palindrome because when we reverse its digits we get 321 which is not equal to 123.

To write a program to check whether it is palindrome,we have to reverse its digits and check whether the number obtained is equal to original number.

We can reverse the digits of a number by using modulus operator(%). It gives remainder of two numbers.
3%2 will give 1, 7%5 will give etc..

so we can reverse a number by following method(lets assume the number is 375

if n is the number n%10 will give its last digit
375%10=5
dividing the number by 10 will remove its last digit(if we declared the variable as integer type)
Therefore when we divide the number by 10 we are left with 37.Again using modulus operator and dividing we get 7 and number left is 3.This step is repeated again and we get all the digits. we can store these digits in an array.Note that we have got the digits in reverse order that is last digit first

Now that all digits are stored in array , the reverse number can generated by multiply the last item in array by 1, second last item by 10,third last by 100 and so on.This step can easily be done by using for loop

Below is a program to check whether a number(between 10000 to 999999) is palindrome.



#include<stdio.h>
#include<conio.h>

int palindrome(int n)
{int i=0,z,sum=0,tota=10;
    int ar[6]={30,30,30,30,30,30};
    if(n>=100000)
    {z=n;
   
    while(n>0)
    {
     ar[i]=n%10;
     n=n/10;
     i++;
     }
     sum=ar[5]+10*ar[4]+100*ar[3]+1000*ar[2]+10000*ar[1]+100000*ar[0];
     if(sum==z)
     return 1;
     else return 0;
     }
     else
     {z=n;
   
    while(n>0)
    {
     ar[i]=n%10;
     n=n/10;
     i++;
     }
     sum=ar[4]+10*ar[3]+100*ar[2]+1000*ar[1]+10000*ar[0];
     if(sum==z)
     return 1;
     else return 0;
     }
     }
     main()
     {int n;
     printf("enter a number between 10000 to 999999 to check whether it is palindrome\n");
     scanf("%d",&n);
     if(palindrome(n)==1)
     printf("it is palindrome");
     else
     printf("it is not a palindrome");
         
           getch();
           }

No comments:

Post a Comment