Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to check given number is PALINDROME or NOT

C Code Example — Loop Programs

ADVERTISEMENT

C Program to check given number is PALINDROME or NOT

Objective

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

Algorithm / Approach

  1. Read an integer n and store a copy of it in temp.
  2. Initialize rev = 0.
  3. Use a while(temp != 0) loop to reverse the number.
  4. Extract the last digit: temp % 10.
  5. Append it to the reverse variable: rev = (rev * 10) + (temp % 10).
  6. Remove the last digit: temp = temp / 10.
  7. After the loop, if rev == n, it is a Palindrome.
main.c
#include<stdio.h>
int main( ) {
 int n, rev = 0, temp;
 printf("Enter Value for N : ");
 scanf("%d", &n);
 temp = n;
 while(temp!=0) {
  rev = rev*10 + temp%10;
  temp = temp/10;
 }
 if(rev == n) {
  printf("N is PALINDROME\n");
 }
 else {
  printf("N is NOT PALINDROME\n");
 }
 printf("\n");
 return 0;
}

Expected Output

Enter Value for N: 1221
N is PALINDROME

Explanation of the Program

  • A Palindrome number reads the same forwards and backwards (e.g., 1221, 12321).
  • To reverse a number mathematically, we extract its last digit using Modulo (% 10). We then push that digit onto our reversed number by multiplying the current reversed number by 10 (shifting it to the left) and adding the extracted digit.

Complexity

Time Complexity O(log₁₀ n) - Proportional to the number of digits.
Space Complexity O(1)
ADVERTISEMENT