English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

/* Reversing a String */
#include
#include
#include
void main()
{
char s[20], r[20];
int i, l, j;
clrscr();
printf("\n Enter A String :");
scanf("%s", s);
l = strlen(s);
for((i=l-1;j=0;i>=0;i--,j++)

{
r[j] = s[i];
}
r[j] = '\0'];
printf("\n Given String : %s", s);
printf("\n Reversed String : %s", r);
if ((strcmp(s,r))==0)
printf("Palindrome");
else
printf("Not Palindrome");
getch();
}

2007-04-26 00:57:07 · 4 answers · asked by robin j 1 in Computers & Internet Programming & Design

4 answers

looks like this line is wrong
for((i=l-1;j=0;i>=0;i--,j++)

i personally dont like doing for loops like this. i would do it this way to make it more readable

j=0;
for(i=l-1;i>=0;i--)
{
r[j] = s[i];
j++;
}

also (just my preference) instead of just using 1 letter for your variable names, give them a name. it also makes it more readable. for instance, instead of l, make it length.

2007-04-26 01:15:15 · answer #1 · answered by justme 7 · 0 0

The logic u used is correct but the statement for loop syntax
is wrong and u taken the string length value to l,it shows the full length of the string before "null" .so u must take i=l in for loop

for((i=l-1;j=0;i>=0;i--,j++) this is ur statement
for(i=l,j=0,i>=0;i--,j++) this is correct syntax

replace this and try it once.

2007-04-26 08:26:41 · answer #2 · answered by raji_badari 2 · 0 0

This will work fine:

int i,len;
scanf("%s",s);
len=strlen(s);
for(i=0;i r[i]=s[len-i-1];
r[i]='\0';
printf("Original string: %s\n",s);
printf("\nReversed string is: %s\n",r);
if(strcmp(r,s)==0)
printf("It is a palindrome\n");
else printf("Not a palindrome\n");

2007-04-26 18:42:56 · answer #3 · answered by Super_moody 2 · 0 0

There is one more logic you can try the following
Check the first half of the value with the second half leaving the middle character in case of odd no.

2007-04-26 08:45:13 · answer #4 · answered by tdrajagopal 6 · 0 0

fedest.com, questions and answers