It seems that I have understood what you need that is what approach you are trying to implement.
You could write the function like
void recuverse( char s[] )
{
recuverse( s , std::strlen( s ) );
}
void recuverse( char s[], size_t n )
{
if ( !( n < 2 ) )
{
std::swap( s[0], s[n-1] );
recuverse( s + 1, n - 2 );
}
}
But it is a wrong solution because it is not function void recuverse( char s[] ); that is a recursive function. It is function void recuverse( char s[], size_t n ); that is recursive. But according to your assignment it is function void recuverse( char s[] ); that shall be recursive.
So the only correct solution is the following.
#include <iostream>
#include <utility>
char * recuverse( char s[] )
{
if ( *s )
{
char *p = s;
do
{
std::swap( *p, *( p + 1) );
} while ( *p++ );
recuverse( s );
std::swap( *p, *( p - 1 ) );
}
return s;
}
int main()
{
char s[] = "abcde";
std::cout << s << std::endl;
std::cout << recuverse( s ) << std::endl;
return 0;
}
The output is
abcde
edcba
This recursive function uses neither standard function except std::swap that you can also substitute for your code.:)
I prefer that the function would have return type char * the similar way as standard C string functions. If you want that the function would have return type void then it will look like
void recuverse( char s[] )
{
if ( *s )
{
char *p = s;
do
{
std::swap( *p, *( p + 1) );
} while ( *p++ );
recuverse( s );
std::swap( *p, *( p - 1 ) );
}
}
For to understand how this reverse function works without standard function strlen let consider its operations step by step using simplified example "abc".
So we have string with terminating zero
abc\0
which I will write as abc0
The while loop
while ( *p++ ) ...
swaps characters until it will swap the terminating zero.
In the first recursive call the loop is doing the following
abc0
bac0
bca0
bc0a
Now the function calls itself but now the string looks like
bc0
So in the loop there will be
bc0
cb0
c0b
In the next recursive call the argument will be
c0
In the loop the two characters are swapped
0c
So at last the function is called with an empty string. So it simply returns the control to the caller and the caller swaps last characters of the string
Take into account that the whole string now looks like
0cba
We need to move the terminating zero tp its valid position at the end of the string. This is done with the swap after the loop.
0c => c0
--------
c0b => cb0
-----------
cb0a => cba0
That is all.:)
void main().