Calculate Palindrome in C:
Take first digit using modulo(%) by 10 in every loop and add it into (previous calculated number*10) and remove first digit using divide(/) by 10.
C program:
#include<stdio.h>
int reverse(int number)
{
int reverse = 0;
int temp;
while(number != 0)
{
temp=number%10;
reverse = reverse*10 + temp;
number = number/10;
}
return reverse;
}
void main()
{
int number=1221;
int check;
check=reverse(number);
if(check==number)
printf("\nNumber is palindrome");
else
printf("Number is not palindrome");
getch();
}
Example of the following C program:
if number is 545.
1. first loop:
temp=545%10=5;
reverse= 0*10+5=5;
number=545/10=54;
2. second loop:
temp=54%10=4;
reverse=5*10+4=54;
number=54/10=5;
3. Third and last loop:
temp=5%10=5;
reverse=54*10+5=545;
number=5/10=0;
Output:
Take first digit using modulo(%) by 10 in every loop and add it into (previous calculated number*10) and remove first digit using divide(/) by 10.
C program:
#include<stdio.h>
int reverse(int number)
{
int reverse = 0;
int temp;
while(number != 0)
{
temp=number%10;
reverse = reverse*10 + temp;
number = number/10;
}
return reverse;
}
void main()
{
int number=1221;
int check;
check=reverse(number);
if(check==number)
printf("\nNumber is palindrome");
else
printf("Number is not palindrome");
getch();
}
Example of the following C program:
if number is 545.
1. first loop:
temp=545%10=5;
reverse= 0*10+5=5;
number=545/10=54;
2. second loop:
temp=54%10=4;
reverse=5*10+4=54;
number=54/10=5;
3. Third and last loop:
temp=5%10=5;
reverse=54*10+5=545;
number=5/10=0;
Output:
Palindrome code Result |
No comments:
Post a Comment