C program for Palindrome Number using do-while Loop

Before going to the program first let us understand what is a Palindrome Number?

Palindrome Number:

                             It is a number which remains same even when the number is reversed.

For example,

Numbers like 0,1,2,11,44,121,222,242,345543 are called as Palindrome Numbers.

Program code to find whether a Number is Palindrome or Not:

#include<stdio.h>
#include<conio.h>
void main()
{
    int n,a,r,s=0;
    clrscr();
    
    printf("\n  Enter The Number:");
    scanf("%d",&n);
    a=n;
    
    //LOOP TO FIND REVERSE OF A NUMBER
    do
    {
        r=n%10;
        s=s*10+r;
        n=n/10;
    }while(n>0);
    
    /* CHECKING IF THE NUMBER ENTERED AND THE REVERSE NUMBER IS EQUAL OR NOT */
    if(a==s)
    {
        printf("\n  %d is a Palindrome Number",a);
    }
    else
    {
        printf("\n  %d is a not Palindrome Number",a);
    }
    getch();
}

Related: C++ program for Palindrome Number using do-while Loop

Working:

  • First the computer reads the number to find the reverse of the number.
  • Then using do-while loop the reverse number is calculated.
  • Then finally the reverse number is compared with the entered number and if they are equal then it is printed as “(Given number) is a palindrome number ” else it is printed as “(Given number) is not a palindrome number “.

Step by Step working of the above Program Code:

Let us assume that the number entered by the user is 121.

  1. It assigns the value of s=0,n=121.
  2. Then it assigns the value of a=n (a=121).
  3. Then the loop continues till the condition of the do-while loop is true.

3.1.    do

r=n%10         (r=121%10)       So  r=1

s=s*10+r     (s=0*10+1)       So  s=1

n=n/10          (n=121/10)      So  n=12

n>0  (12>0)  do-while loop condition is true

3.2.    do

r=n%10         (r=12%10)       So  r=2

s=s*10+r     (s=1*10+2)       So  s=12

n=n/10          (n=12/10)        So  n=1

n>0  (1>0)  do-while loop condition is true

3.3.    do

r=n%10         (r=1%10)        So  r=1

s=s*10+r     (s=12*10+1)      So  s=121

n=n/10          (n=1/10)         So  n=0

n>0  (0>0)  do-while loop condition is false

3.4.    It comes out of the while loop and checks whether the number is palindrome or not.

  1. a==s  (121==121)   if condition is true

It prints 121 is a palindrome number.

  1. Thus the program execution is completed.

In the above working, step:4 if condition can also be false for some other number like ’12’.

Then for that it goes to the else part and prints 12 is not a palindrome number.

Output:

palindrome number

palindrome number

TO DOWNLOAD THE PROGRAM CODE : CLICK HERE

 

Leave a Reply

Your email address will not be published. Required fields are marked *