# Thread: string reversion using recursion

1. ## string reversion using recursion

hello guys im practicing my recursion skills and i found this problem somewhere
that wants to reverse a string recursively so if we have for example "abc" it will make it "cba"

this is my try

Code:
```#include <stdio.h>
char reverse(char a[], int n,int k){
char t;
if (n==(k-1) || n==k){
return;
}
t = a[n];
a[n] = a[k];
a[k] = t;

return reverse(a,n-1,k+1);

}

int main(void){

char x[] = "HELLO WORLD";
reverse(x,strlen(x)-1,0);
printf("%s\n",x);
getchar();
return 0;

}```
tell me what you think about it, also if you can tell me how to make it better maybe use less variables or stuff like that

Different code versions of this problem would be highly appreciated too 2. You can't have a function defined to return a type, and then return nothing. Compile with warnings on and fix them as you encounter them.

Quzah. 3. Try something like this, in the first function:

Code:
```void reverse(char *s)
{
swapRecursive(s, strlen(s));
}```
And then write the other function, swapRecursive, which swaps the elements recursively (just pass it s+1 addres, len - 2 length every time).

I think i have the code for it, somewhere, if you'd like ill post it.

You cant do it in just one function if you want to have O(n) time by the way (fastest possible).

If you're really into geting this function right, check my profile - there's a topic which i posted for this subject as well and got nice answers . 4. Close try, but you don't necessarily need to return anything on the reverse function as you can just modify the array inside the function and it'll be affected in the main function. You can reduce variable usage by using XOR to do your swaps:

Code:
```void reverse(char* a, int n, int k) {
if (n >= k) return;
a[n] ^= a[k] ^= a[n] ^= a[k];
reverse(a, n+1, k-1);
}

int main()
{
char x[] = "HELLO WORLD";
reverse(x, 0, strlen(x)-1);
printf("%s\n",x);
return 0;
}``` 5. Code:
`a[n] ^= a[k] ^= a[n] ^= a[k];`
This is undefined behavior (modifying a[n] twice with no intervening sequence point). If you really want to use the XOR technique, it needs to be split up into separate statements. But using a temporary makes what you're doing clear. There's no point in trying to optimize something like this unless you're sure it's an actual bottleneck of some sort. Popular pages Recent additions 