Tuesday, June 1, 2010

PALINDROME PROGRAM IN C++ WITH EXPLANATION.. This will be correct logic which everyone expects



 What we have to do is
i)                    Find the length of the string
ii)                   Divide the length of the string by 2. Because from the first element in the array we should go until the predecessor of middle element and then from the last we go until the successor of the middle element Take this as an example
If this is the input string “LIRIL”. Here the middle element is a[3] = ‘R’, to find whether it is palindrome or not we should check as given in the diagram. Then we should compare the last element and with the first element. Like        

1.      We check the last element a[5] and the first element a[1].
2.      We check the second from the first a[2] with the second from the last a[4].
              
                  Middle element need not to be checked because it positions will not be changed if the string is reversed. This the logic behind this program.

If the length of the string is even( EG, 4 OR 8 OR 10) then there will be no middle element as given in the above example.

For eg) for the string “KAIL

                        

void main()
{
 int i,j,n=0,n1,cnt=0;
 char a[20];
 clrscr();
 printf("\n ENTER THE STRING : ");
 cin>>a;

// Here we get calculate the length of the string
 while(a[n]!='\0')
 {
 n =n+1;
 }
// Completes here

// To find the middle value. If the length is a even number it takes the value 0.
 n1 = n/2;
//completes here

/* This loop check the a[i] before n1 with a[j] until before n1. Remember a[i] starts from the first and b[j] starts from the last index */

for(i=0,j=n-1; i < n1 && j  >  n1; i++, j--)
 {
   if(a[i] == a[j])
    cnt++;
  else
  {
   printf("\n THE STRING IS NOT A PALINDROME");
   break;
  }
 }
 if(cnt == n1)
  printf("\n THE STRING IS A PALINDROME");
getch();
}

1 comment:

  1. Palindrome Number Program in C++

    A Palindrome number is a number that remains the same when its digits are reversed. Like 16461, for example: we take 121 and reverse it, after revers it is same as original.

    ReplyDelete