Palindrome of string in c without using library functions -
i created code palindrome of string using reverse , copy of strings without library function.but still shows palindrome.what mistake have done.and prints palindrome regardless whether give palindrome or not.i checked internet code want know mistake made in code please help.
#include <stdio.h> #include <string.h> int main() { char s[1000]; char t[1000],temp; int i,j,flag=0; gets(s); for(i=0;i<strlen(s);i++) { t[i]=s[i]; } printf("%s",t); int n=strlen(s)-1; for(j=0,i=n;i>=0;j++,i--) { t[j]=s[i]; } printf("%s",t); for(i=0,j=0;i<=n,j<=n;i++,j++) { //for(j=0;j<n;j++){ if(t[j]==t[i]) { flag=1; break; } } if(flag==1) { printf(" palindrome"); } else { printf("else palindrome"); } return 0; }
not preventing using library functions, mistakes in code are:
gets()
, has unavoidable risk of buffer overrun, deprecated in c99 , removed c11, used.- undefined behavior invoked @
printf("%s",t);
, pointer not null-terminated string passed use%s
. - the condition
t[j]==t[i]
wrong because same things compared. - you used
flag
check if "at least one of characters same". should check "all of characters same".
try this:
#include<stdio.h> #include<string.h> int main(void) { char s[1000],*lf; char t[1000],temp; int i,j,n,flag=1; /* use fgets() instead of gets() */ fgets(s, sizeof(s), stdin); if((lf=strchr(s, '\n'))!=null) { *lf = '\0'; } n=strlen(s); for(i=0;i<n;i++) { t[i]=s[i]; } /* terminate string */ t[n]='\0'; printf("%s",t); n=strlen(s)-1; for(j=0,i=n;i>=0;j++,i--) { t[j]=s[i]; } printf("%s",t); for(i=0;i<=n;i++) { /* check if characters same */ if(s[i]!=t[i]) { flag=0; break; } } if(flag==1) { printf(" palindrome"); } else { printf("else palindrome"); } return 0; }
library functions not avoided in code. can avoid using them implementing (somewhat) equivalent them , replacing usage of library functions implimentation.
Comments
Post a Comment