Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to check the given number is PALINDROME or NOT

C++ Code Example — Loop Programs

ADVERTISEMENT

WAP to check the given number is PALINDROME or NOT

Objective

Write a C++ program to check if a given number is a Palindrome.

Algorithm / Approach

  1. Read a number n and store a backup copy in orig.
  2. Initialize rev = 0.
  3. In a while(n > 0) loop, extract the last digit: temp = n % 10.
  4. Append it to the reverse variable: rev = (10 * rev) + temp.
  5. Chop off the last digit: n = n / 10.
  6. Compare the built rev number against the orig backup.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int n,orig,rev = 0;
 cout<<"Enter Value for N: ";
 cin>>n;
 orig = n;
 while(n>0) {
  int temp = n%10;
  rev = 10*rev+temp;
  n = n/10;
 }
 if(orig==rev) {
  cout<< orig<<" is Palindrome\n";
 }
 else {
  cout<< orig<<" is not Palindrome\n";
 }
return 0;
}

Expected Output

Enter Value for N: 12345
12345 is not Palindrome

Explanation of the Program

  • A Palindrome number reads the same forwards and backwards (e.g., 12321).
  • By using the modulo operator (% 10), we extract the right-most digit. By multiplying our running total by 10 before adding the new digit, we mathematically shift all previously extracted digits to the left, perfectly constructing the number in reverse.

Complexity

Time Complexity O(log₁₀ n)
Space Complexity O(1)
ADVERTISEMENT