Subscribe

RSS Feed (xml)

Thursday, January 8, 2009

Write a C program to determine if the given string is a Palindrome or not without using library functions

/* Palindrome string means
ie., string = after reverse
given string= reverse string (then it is said to be palindrome string). */

#include(stdio.h) // place this '<' & '>' instead of '(' & ')' before stdio.h
#include(conio.h)
int main(void)
{
char st[10], rev[10];
int i, len, flag;
clrscr( );
printf("Enter the required string: ");
scanf(" %s", st); // (or) gets(st);
for(i=0; st[i ]!='\0' ; i++ ); //to find the length of a given string
len=i -1;
for(i=0; st[i ]!='\0' ; i++) // to store the given string in reverse
{
rev[i ]=st[ len];
len--;
} rev[i]='\0';
flag=0;
for(i=0; st[i ]!='\0'; i++) // to compare the given and reverse strings.
{
if( st[i] !=rev[i ] ) { flag=1; break; }
}
if(flag==0)
printf("\nPalindrome string");
else
printf("\nNot a palindrome string");
getch( );
return 0;
}

Explanation:-
Here 'flag' value will tells that whether the given string is palindrome string or not.
ie., if(st[i] !=rev[i ]) { flag=1; break; }
The above statement is true, when the value of 'st' variable is not equal to 'rev' variable. So if the condition is true, then the control enter inside the block. First 'flag' value becomes One and the loop will terminate.
Therefore, the result palindrome will be displayed when 'flag value is zero'.

No comments:

Post a Comment