Friday, October 14, 2011

Program to check if a number is palindrome or not in C

Objective : To check if given number is palindrome or not in C.
Programming logic : This is a very easy program if you know how to reverse a number. Once you have found the reverse of number just compare it with original, if both are same then the number is palindrome.

Code:
#include<stdio.h>
int main()
{
    int k;
    printf("\n enter number =");
    scanf("%d",&k);
    if(palindrome(k))
    {
        printf("\n The number is palindrome");
    }
    else
    {
        printf("\n The number is not palindrome");
    }
    return(0);
}
int palindrome(int x)
{
    int rev=0;//to calculate reverse of number
    int k=x;
    while(k>0)
    {
        rev=rev*10+k%10;
        k=k/10;
    }
    if(x==rev)// check if reverse is equal to given number
    {
        return(1);//if yes then return 1
    }
    else
    {
        return(0);//else return 0
    }
}

No comments:

Post a Comment