Mynicks
Mynicks

Reputation: 223

Recursion: Reverse string in its position

Recursion. I checked other online solutions and they seem to be pretty much identical to mine. The code should reverse the string (in its position) but it does not. E.g when input is st2 = "abcdefg" the output is an empty string. I was expecting st2 = "gfedcba". What am i missing?

#include <stdio.h>
#include <string.h>


void recurse_reverse(char s[], int sz)
{
    int i=0,j = sz -1;
    if(i<j)
    {
        swap(&s[i],&s[j]);
        recurse_reverse(s+1, sz-2);

    }
}


void swap( char* s1, char *s2)
{
    char tmp;
    tmp = *s1;
    *s1 = *s2;
    *s2 = tmp;
}


int main(void)
{
    char st1[9] = "abcdefg", st2[9];
    strcpy(st2,st1);
    recurse_reverse(st2,9);
    printf("s1 = %s\ns2 = %s",st1,st2);
    printf("\n" );
    return 0;
}

Upvotes: 4

Views: 153

Answers (3)

Vinay Shukla
Vinay Shukla

Reputation: 1844

I added a printf statement to debug the issue and got the below output. You are trying to access 9th variable which is a terminated null character \0 hence you only get \0 as output and not the actual reversed string.

Instead of hardcoding the size of string you can use strlen to get the string length.

1st char = a and 9th char is ▒
1st char = b and 9th char is
1st char = c and 9th char is g
1st char = d and 9th char is f
s1 = abcdefg
s2 = ▒

Solution

Intended code change

recurse_reverse(st2,strlen(st1));

Output

1st char = a and 9th char 9th char is g
1st char = b and 9th char 9th char is f
1st char = c and 9th char 9th char is e
s1 = abcdefg
s2 = gfedcba

Upvotes: 3

Sumit Gemini
Sumit Gemini

Reputation: 1836

#include <stdio.h>
#include <string.h>

void swap( char* s1, char *s2);

void recurse_reverse(char s[], int sz)
{
    int i=0,j = sz-1;
    if(i<j)
    {
        swap(&s[i],&s[j]);
        recurse_reverse(s+1, sz-2);

    }
}


void swap( char* s1, char *s2)
{
    char tmp;
    tmp = *s1;
    *s1 = *s2;
    *s2 = tmp;
}


int main(void)
{
    char st1[9] = "abcdefg", st2[9];
    int len=0;
    strcpy(st2,st1);
    len =strlen(st2);
    recurse_reverse(st2,len);
    printf("s1 = %s\ns2 = %s",st1,st2);
    printf("\n" );
    return 0;
}

Upvotes: 1

P.P
P.P

Reputation: 121377

You are swapping the 2 zero bytes at the end of st1. Hence, the st2 starts with a null byte and thus the printf() isn't printing anything. You just need to fix your argument passing. Instead of

recurse_reverse(st2,9);

do

recurse_reverse(st2,strlen(st1));

You probably want to add logic to make sure your destination array st2 has sufficient space.

Upvotes: 5

Related Questions