Search code examples
crecursionreversec-stringsfunction-definition

reverse a character in array using recusion in C


this is my recursion function

void reverseArray(char *str,int len)
    {
        char temp;
        if(len==(0.5*len))
        {
            return;
        }
        temp=*(str+len-1);
        *(str+len-1)=*str;
        *str=temp;
        reverseArray(str+1,len-1);
    }

iam trying to reverse the charcters but when i send {'1', '2', '3', '4', '5', '6','7'} to function i always get 7123456 only the last charcter become first the other not changing .


Solution

  • In this call

    reverseArray(str+1,len-1);
    

    the second argument is incorrect. You have to write

    reverseArray(str+1,len-2);
    

    Also instead of this condition

    if(len==(0.5*len))
    

    it is much better to write

    if ( len < 2 )
    

    The function can look the following way

    void reverseArray( char *str, size_t n )
    {
        if ( !( n < 2 ) )
        {
            char tmp = *str;
            *str = *( str + n - 1 );
            *( str + n - 1 ) = tmp;
    
            reverseArray( str + 1, n - 2 );
        }
    }
    

    Or

    char * reverseArray( char *str, size_t n )
    {
        if ( !( n < 2 ) )
        {
            char tmp = *str;
            *str = *( str + n - 1 );
            *( str + n - 1 ) = tmp;
    
            reverseArray( str + 1, n - 2 );
        }
    
        return str;
    }
    

    Pay attention that the function strlen or the operator sizeof returns a value of the type size_t. This type you should use to specify the length of a character array instead of the type int.

    For example the last function can be called like

    char str[] = "Hello World!";
    puts( reverseArray( str, strlen( str ) ) );