Introduction
In this lab, we will learn to write a C program to check whether a number is a palindrome or not. We will accomplish this by following the given steps.
Note: You need to create the file
~/project/main.cyourself to practice coding and learn how to compile and run it using gcc.
cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main
Understanding Palindrome
Palindrome is a number or a string in which, when read from the front and from the rear, it reads the same. For example: 121 or "racecar".
Initializing Variables
We start by initializing the required variables for the program. In the given program, we have used three variables, a, b, c, s. We will be using these variables to perform the required operations.
#include<stdio.h>
int main()
{
int a, b, c, s = 0;
printf("Enter a number: ");
scanf("%d", &a);
c = a;
}
Reversing the number
We reverse the number so that it can be compared with the original number to check whether it is a palindrome or not. We use a while loop to reverse the number.
while(a > 0)
{
b = a % 10; //extract last digit
s = (s * 10) + b; //add the last digit to the reversed number
a = a / 10; //remove the last digit from the original number
}
Comparing the original number with reversed number
Finally, we compare the reversed number with the original number to check whether it is a palindrome or not.
if(s == c)
{
printf("%d is a Palindrome", c);
}
else
{
printf("%d is not a Palindrome", c);
}
Full Code
Here is the full code of the program,
#include<stdio.h>
int main()
{
int a, b, c, s = 0;
printf("Enter a number: ");
scanf("%d", &a);
c = a;
while(a > 0)
{
b = a % 10;
s = (s * 10) + b;
a = a / 10;
}
if(s == c)
{
printf("%d is a Palindrome", c);
}
else
{
printf("%d is not a Palindrome", c);
}
return 0;
}
Summary
In this lab, we have learned to write a C program to check whether a number is a palindrome or not. We learned the logic behind palindrome checking and implemented it in the program. We now have a better understanding of this concept and can now implement it in more complex programs.



