Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to find palindrome number by using while loop
A palindrome number is a number which remains the same when its digits are reversed. For example, 121, 1331, and 7557 are palindrome numbers. In C programming, we can check if a given number is a palindrome by using a while loop to reverse the number and then comparing it with the original.
Syntax
while (condition) {
// Extract last digit
remainder = number % 10;
// Build reversed number
reversed = reversed * 10 + remainder;
// Remove last digit
number = number / 10;
}
Example 1: Palindrome Number Check
Following is the C program to find palindrome number by using the while loop −
#include <stdio.h>
int main() {
int num, temp, rem, rev = 0;
printf("Enter a number: ");
scanf("%d", &num);
temp = num;
while (temp > 0) {
rem = temp % 10;
rev = rev * 10 + rem;
temp = temp / 10;
}
printf("Reversed number is = %d<br>", rev);
if (num == rev)
printf("%d is a Palindrome Number.<br>", num);
else
printf("%d is not a Palindrome Number.<br>", num);
return 0;
}
Enter a number: 1234 Reversed number is = 4321 1234 is not a Palindrome Number.
Example 2: String Palindrome Check
Here is another example to check palindrome for strings using while loop −
#include <stdio.h>
#include <string.h>
void checkPalindrome(char string[]);
int main() {
char string[100];
printf("Enter a string: ");
fgets(string, sizeof(string), stdin);
// Remove newline character if present
string[strcspn(string, "<br>")] = '\0';
checkPalindrome(string);
return 0;
}
void checkPalindrome(char string[]) {
int i = 0;
int length = strlen(string) - 1;
while (length > i) {
if (string[i++] != string[length--]) {
printf("%s is not a palindrome<br>", string);
return;
}
}
printf("%s is a palindrome string<br>", string);
}
Enter a string: level level is a palindrome string
How It Works
The algorithm works by extracting digits from the original number one by one using the modulo operator (%) and building the reversed number. The while loop continues until all digits are processed, then we compare the original and reversed numbers.
Conclusion
Using while loops to check palindrome numbers is an efficient approach that reverses the digits systematically. This method works for both numeric and string palindromes with proper digit extraction and comparison logic.
