####
Number Palindrome :

#### Suppose consider a number 121, the reverse of that number is 121 Hence we can say 121 is a palindrome.Similary some other examples 111,101....

So to check this first we need to reverse the number.We can see the logic in program how to reverse and compare.

#include <stdio.h> void main() { int num, temp, remainder, reverse = 0; printf("Enter an integer \n"); scanf("%d", &num); /* original number is stored at temp */ temp = num; while (num > 0) { //Here is main logic remainder = num % 10; reverse = reverse * 10 + remainder; num /= 10; } printf("Given number is = %d\n", temp); printf("Its reverse is = %d\n", reverse); if (temp == reverse) printf("Number is a palindrome \n"); else printf("Number is not a palindrome \n"); }

Input : 121

Output: Number is a palindrome

In that main logic suppose consider an example 121:The loop goes as follows.

#### iteration1:

num = 121 > 0 so it executes the loop

remainder = 121%10=1

reverse = 0 * 10 +1 = 1

num = 121/10 = 12

#### iteration2:

num = 12 > 0 so it executes the loop

remainder = 12%10=2

reverse = 1* 10 +2 = 12

num = 12/10 = 1

#### iteration3:

num = 1 > 0 so it executes the loop

remainder = 1%10=1

reverse = 12* 10 +1 = 121

num = 1/10 =0

Now again check for 0 > 0 at while loop condition it fails and the reverse=121 now is reverse of the input number.

Now compare original number in temp and reverse, if they are same then it is a palindrome else it is not a palindrome.

## No comments:

## Post a Comment