Pages - Menu

Find whether the number entered by user is palindrome or not (C++ example)

Hello everyone! I know I was long gone and haven't posted here for long time, but I am back.

Guess what???

Final exams are over and I am here with some programming stuff and some other things are also in queue, which I missed.

Here is a program in C++ which can process the number submitted by user and tells whether it is a palindrome number or not. It is really basic and simple example with simple logic behind it. Have a look on the program code in C++ below:

#include "iostream"
#include "conio.h"
using namespace std;
int main()
    int value, v, reverse=0, r=0;
    cout << "Type the number to find if it is palindrome: ";
    cin >> value;
    v = value;
    while(value != 0)
        r = value%10;
        value = value/10;
        reverse = reverse*10 + r;
    cout << "Reverse of " << v << " is " << reverse << "." << endl;
    if(reverse == v)
        cout << v << " is palindrome number." << endl;
        cout << v << " is not palindrome number." << endl;
 cout << "Type any key to exit. . .";
    return 0;

What is palindrome number?

The number which reads the same backward or forward.

How above program works?

Four variables are declared with 0 as value of reverse integer variable is essential one, because it'll be used in the program to produce results dynamically.

Number input is stored in value variable, value of value variable is also assigned to the v variable for comparison purposes.

While loop is used to get the reverse of the number. Value stored in value variable is reduced as while loop iterates.

What is happening inside while loop?

In while loop remainder of value is assigned to the r variable. Number stored in value is reduced and its last digit is removed. Actually last digit is already stored in r variable as remainder and last statement in the while loop can be understood easily. For the first time 10 is multiplied by 0 and added to the remainder (0 multiplied by anything results 0).
In second iteration last stored value is multiplied with 10 and remainder is added to it.

When value is reduced to 0, while loop stops and statements after while loop are executed which are really easy to understand.
Reverse of the number is shown. Then if reversed value is equal to the value submitted by user then message is shown that number is palindrome.

I hope explanation made this program easy to understand. Feel free to ask anything about this code or if there is something wrong with above program, let me know.
Take care and remember me in your prayers.

Green forest with light sun.

Picture: Wikimedia Commons