Could anyone help me writing this function recursively?
I know how to write it without recursion.
Code:void Reverse2(char s[]) { int c, i, j; for(i = 0, j = strlen(s)-1; i<j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } }
Could anyone help me writing this function recursively?
I know how to write it without recursion.
Code:void Reverse2(char s[]) { int c, i, j; for(i = 0, j = strlen(s)-1; i<j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } }
Search the cboard for plenty of similar posts.
I think i did it, but it uses pointers! Is there a way to do this without pointers?Code:void reverse(char *s, int len) { if(len <= 0) return; int temp = s[0]; s[0] = s[len-1]; s[len-1] = temp; reverse(s + 1, len - 2); }
Last edited by Tool; 12-27-2009 at 08:59 AM.
Not really. The problem is that since in many contexts an array is converted to a pointer to its first element, completely avoiding pointers when working with arrays is practically impossible.Originally Posted by Tool
Of course, you can try to avoid pointer notation further by passing an index along with a pointer to the first character of the array, but that is not so elegant.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
What about this:
Uses static int instead of pointers.Code:void reverse2(char s[]) { static int i = 0; static int j = strlen(s); if(j <= strlen(s) / 2) return; char temp = s[i]; s[i] = s[j-1]; s[j-1] = temp; i++, j--; reverse2(s); }
That is just horrible. Does it even compile? If it does, how are you going to reuse the function?
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Oh, your right. I forgot static works only for the first call.
Ill just go with the pointer version then .