Check Whether a Number Is a Palindrome Using a While Loop in C

This program checks whether a given number is a palindrome (reads the same forwards and backwards) using a while loop.

C Program

#include <stdio.h>

int main() {
    int num, original, reversed = 0, remainder;

    printf("Enter a number: ");
    scanf("%d", &num);

    original = num;

    while (num != 0) {
        remainder = num % 10;
        reversed = reversed * 10 + remainder;
        num = num / 10;
    }

    if (original == reversed) {
        printf("%d is a palindrome.\n", original);
    } else {
        printf("%d is not a palindrome.\n", original);
    }

    return 0;
}

Explanation

  • The original number is preserved in original since num gets modified during reversal.
  • Inside the while loop, num % 10 extracts the last digit, which is appended to reversed by reversed * 10 + remainder.
  • num / 10 removes the last digit (integer division), and the loop continues until num becomes 0.
  • Finally, the reversed number is compared with the original — if they match, the number is a palindrome.

Sample Output

Enter a number: 12321
12321 is a palindrome.

Enter a number: 12345
12345 is not a palindrome.

Leave a Comment