Search code examples
c++loopsmathpalindrome

checking if number is a palindrome in C++


/*
  david ballantyne
  10/10/13
  assesment lab 2
*/

//Libraries
#include <iostream>


//Global Constants

//Functioning Prototypes
using namespace std;

int main() {
         int n, num, digit, rev = 0;
         cout << "Enter a positive number"<<endl;
         cin >> num;
         num=n;

         do{
             digit = num%10;
             rev = (rev*10) + digit;
             num = num/10;

}
    while (num!=0);
         if (n == rev)
         cout << " The number is a palindrome"<<endl;
        else
         cout << " The number is not a palindrome"<<endl;
return 0;
}

I enter a palindrome and it keeps telling me it's not a palindrome, also if you could help me understand what kind of loop I would use to ask a "would you like to try again y/n" I'd be grateful.


Solution

  • cin >> num;
    num=n;
    

    assigns a user-specified integer to num then replaces it with the value of the uninitialised variable n

    Did you mean to reverse the assignment

    n=num;
    

    instead?

    also if you could help me understand what kind of loop I would use to ask a "would you like to try again y/n"

    You could use a do...while loop with the condition for the while being calculated after you report whether the number was a palindrome.