Wednesday, 7 September 2016

String Palindrome without Library function

Write a function that accepts a string and returns 1 if the string is palindrome else 0 if string is not a palindrome without using any built in functions.

#include<stdio.h>
int palindrome(char str[10])
{
                int i, j;
                i=0;
                while(str[i]!='\0')
                {
                                i++;
                 }
                for(j=i-1, i=0;   j>=0;    j--,i++)
                {
                                if(str[i] != str[j])
                                return 0;
                }
                return 1;
}
void main()
{
                char str[10];
                int p;
                printf("\nEnter a string:   ");
                gets(str);

                p=palindrome(str);
                if(p)
                                printf("\nString is palindrome");
                else
                                printf("\nString is not palindrome");
}
Output:
Enter a string:   abcde
String is not palindrome

Enter a string:   abcba
String is palindrome


Method 2:
#include <stdio.h>
int main()
{
                char string[20];
                int i, length;
                int flag = 0;
                printf("Enter a string:");
                scanf("%s", string);

                length=0;
                while(string[length]!='\0')
                                length++;

                for(i=0;i < length ;i++)
                {
                                if(string[i] != string[length - i - 1])
                                {
                                                flag = 1;
                                                break;
                                }
                }
                if (flag)
                                  printf("\nstring is not a palindrome");
                else
                                  printf("\nstring is a palindrome");
  

}