Thursday, 9 June 2016

Check a string is palindrome without using library functions

Palindrome string is a string which reads the same forward or backward.
eg    LEVEL 

Place i on the start of string and j on the end of the string.Compare the characters.Only if they match we proceed or it is not a palindrome.If they match increment i and decrement j.Repeat the same process.If i equals   i.e all characters matched.So it is a palindrome.

Code

#include<stdio.h>

int main()
{
    char s[20];
    int i,j;

    printf("Enter a string : ");
    scanf("%s",s);

    //Position i and j

    i = 0;
    j = 0;  

    while (s[j] != '\0')
            j++;

    j--;          

    for(;i<j;i++,j--)
    {
        if(s[i] == s[j])
            continue;
        else
        {
            printf("\nNot a palindrome");
            break;
        }
    }
    if(i == j)
        printf("\nPalindrome");

    return 0;
}


O/P



Code Tracing

                         s[]                              

                  i               j                 
                  l   e   v   e   l                  Identical.Inc start,Dec end.


                      i       j
                  l   e   v   e   l                  Identical.Inc start,Dec end.


                         i,j
                  l   e   v   e   l                  i == j.   Palindrome


No comments:

Post a Comment