### Recursive function to reverse an array

Wish to know how to reverse an array recursively. My code is definitely a mess. Best if a solution is pass by pointers as my main program too.

 ``12345678910111213141516171819202122232425262728293031`` ``````#include #include using namespace std; void reverse(char*p1, char*p2, int n = 0) { if(p2 > p1) { return ; } else { //swap?? char* temp = p1; p1 = p2; p2 = temp; cout << "p1 = " << p1 << "p2 = " << p2 << endl; reverse(p1-n+1,p2-n-1); } } int main() { char str[] = "Hello"; cout << str << endl; reverse(&str[0], &str[strlen(str) - 1]); cout << str << endl; } ``````
use std::swap from the header <algorithm>
EDIT: Why on Earth would you use POINTERS????
Last edited on
 Why on Earth would you use POINTERS????

O.o
I don't like using pointers, but this question is a homework practice, for recursion
Pointers are a pretty big part of programming, I'd start learning to like them. They aren't some mysterious magical device used to confuse you, they're used all over the place in computers.
> Best if a solution is pass by pointers

You don't need that `int n = 0`, do you?

 ``12345678910111213141516`` ``````#include void reverse( char* first, char* last ) { if( first < last ) { std::swap( *first, *last ) ; reverse( first+1, last-1 ) ; } } int main() { char cstr[] = "hello world!" ; reverse( cstr, cstr + sizeof(cstr) - 2 ) ; }``````
Another realization of the function

 ``123456789101112131415161718192021222324252627`` ``````include #include using namespace std; void reverse( char *s, int n ) { if ( n < 2 ) { return ; } char c = s[0]; s[0] = s[n-1]; s[n-1] = c; reverse( ++s, --n ); } int main() { char str[] = "Hello"; cout << str << endl; reverse( str, strlen( str ) ); cout << str << endl; }``````
I wonder ... instead of using `int n` couldn't you just check to see if `*s == '\0'` ?
Last edited on

@TwoOfDiamonds

 I wonder ... instead of using int n couldn't you just check to see if *s == '\0' ?

It is possible only for the first recursive iteration. And what about subsequent iterations?!

Last edited on
Thanks for every answers given. Like what I said my code is a mess that int n=0 is just a code that I reference from other questions.
Last edited on
Topic archived. No new replies allowed.