- Enter a number to assign to the n variable:
printf("Enter a number ");
scanf("%d",&n);
- Invoke the findpalindrome function and pass the number in the n variable to it as an argument:
findpalindrome(n)
- The n argument is assigned to the numb parameter in the findpalindrome function. We need to separate each digit of the number; to do so, we will execute a while loop for the time the value in the numb variable is greater than 0:
while(numb >0)
- Within the while loop, we will apply mod 10 on the number. On application of the mod 10 operator, we will get the remainder, which is basically the last digit of the number:
remainder=numb%10;
- Push that remainder to the stack:
push(remainder);
- Because the last digit of the number is separated, we need to remove the last digit from the existing number. That is done by dividing the number by 10 and truncating the fraction. The while loop will terminate when the number is individually divided into separate digits and all the digits are pushed to the stack:
numb=numb/10;
- The number at the top of the stack will be the hundred and the one at the bottom of the stack will be the unit of the original number. Recall that we need to convert the hundred of the original number to the unit and vice versa. Pop all the digits out from the stack one by one and multiply each of them by 10 raised to a power. The power will be 0 for the first digit that is popped off. The power will be incremented with every value that is popped off. After being multiplied by 10 raised to the respective power, the digits are added into a separate variable, called value:
j=pop();
value=value+j*pow(10,count);
count++;
- If the numbers in the numb and value variables match, that means the number is a palindrome. If the number is a palindrome, the findpalindrome function will return a value of 1, otherwise it will return a value of 0:
if(numb==value) return (1);
else return (0);
The findpalindrome.c program determines whether the entered number is a palindrome number:
//Find out whether the entered number is a palindrome or not
# include <stdio.h>
#include <math.h>
#define max 10
int top=-1;
int stack[max];
void push();
int pop();
int findpalindrome(int);
void main()
{
int n;
printf("Enter a number ");
scanf("%d",&n);
if(findpalindrome(n))
printf("%d is a palindrome number",n);
else
printf("%d is not a palindrome number", n);
}
int findpalindrome(int numb)
{
int j, value, remainder, temp,count;
temp=numb;
while(numb >0)
{
remainder=numb%10;
push(remainder);
numb=numb/10;
}
numb=temp;
count=0;
value=0;
while(top >=0)
{
j=pop();
value=value+j*pow(10,count);
count++;
}
if(numb==value) return (1);
else return (0);
}
void push(int m)
{
top++;
stack[top]=m;
}
int pop()
{
int j;
if(top==-1)return(top);
else
{
j=stack[top];
top--;
return(j);
}
}
Now, let's go behind the scenes.