palindromic numbers

Is there a way to make the program stop when a variable is a palindromic number? A palindromic number is a number that is the same if u read it either forward or backward. Some examples are: 101 & 9009.
closed account (1yR4jE8b)
insert the number into a std::stringstream then call the .str method to create a string of that number, then check if that string is a palindrome.
Yes there is. You could store the number to a string or character array and then use a recursive function to check the start end the end positions for equality, then repeat until reach the center of the string, in which case you will know whether the number is a palindrome or not.
im sorry but neither of the 2 replies above make sense to me. Im a somewhat new programmer. I tried looking up what all that stuff meant but it just doesnt make sense. If someone could explain more that would be helpful. thanks..
Last edited on
Sure.

Here are the steps:

1) Get number.
2) Check if number is palindromic.
3) If it is, stop program.
4) If it is not, get next number and go back to step 2.

Code up what you can, and when you get stuck, ask.
I would process each string into an character array. Compare the array from both ends for equivalency.

so:

Compare char[0] to char[arrayLength-1] for equality.

Add one to the initial and subtract one from the second until either left > right or left == right.

If all values evaluate to true, you have a palindrome, and you can break the loop you are cycling (probably a for or a while loop), else, keep cycling the numbers.

Need code?
I think this is what you are looking for :

#include "stdafx.h"
#include <iostream>

using namespace std;
bool ispalindrome(char *str);
int main()
{
char s[10];
char ans;
do
{
cout<<"Enter the variable\n";
cin>>s;
if(ispalindrome(s))
{
cout<<"Entered Text is a palindrome\n";
cout<<"Exiting program...";
break;
}
else
{
cout<<"Entered Text is not a palindrome\n";
}
cout<<"Do you want to continue? Press Y/y to continue.\n";
cin>>ans;
}while((ans == 'y') ||(ans == 'Y'));
}

bool ispalindrome(char *str)
{
int i,j;

for(i = 0,j =(strlen(str)-1); i<(strlen(str)/2);i++,j--)
{
if((str[i] )!= (str[j]))
{
return false;
}
}
return true;
}
Topic archived. No new replies allowed.