Thursday, June 18, 2009

Reversing a string, without additional memory

#include

int main()
{
char ch;
int i, j;
char s[10];
gets(s);
//count string length
for(j = 0; s[j] != '\0'; j++);
--j;
// now j has string lentgth

for(i = 0; i < j; i++)
{
*(s+j) = *(s+i)+*(s+j);
*(s+i) = *(s+j)-*(s+i);
*(s+j) = *(s+j)-*(s+i);
--j;
}

printf("Reversed: %s", s);
return 0;
}


So the sample output can be,
$ ./a.out
sample
elpmas

Cheers.

2 comments:

shobana said...

see #include ?....

shobana said...

i compiled it..really nice