-1

I want to write a recursive function in C languge that revers a word. I know how to do it with printing it, but actually reversing the original word I don't know how. so, I want to write a function that revers a word, using pointers, using string.h, but has to be void, no printing, and changing the original word. the function prototype: void reverse(char* string); what I was able to write were the stop terms of the recursion(and i'm not sure if they are correct);

if(!string) return; // if the string is empty
if(*(string+1)=='\0' return (*string); // if there is only on char in the string
if(*(string+2))=='\0' // if there are only 2 letters In the strings-swap
temp=(*string);
(*string)= * (string+1);
(*string+1)= temp; // I don't know what to do after..

that would be great is go guys can explain to me what to do. thank you.

6
  • It would be useful if you add a function head to see the interface as well as the local variable definitions. Commented Jan 3, 2015 at 11:13
  • Are you want answer in recursion calling or loop? Commented Jan 3, 2015 at 11:23
  • @Karthikeyan.R.S recursion calling Commented Jan 3, 2015 at 11:42
  • Is this supposed to reverse the words in a sentence, or reverse a string ? Your description is unclear. "Reversed Words In A Sentence" ==> "Sentence A In Words Reversed". Whereas, "Reverse A String" ==> "gnirtS A esreveR". Which is it exactly? (Note, the former is considerably more difficult than the latter). Commented Jan 3, 2015 at 12:21
  • @ WhozCraig you are right, it's not clear.. I just edited it. just reversing a one word.. not in a sentence. Commented Jan 3, 2015 at 12:42

3 Answers 3

0

An implementation with tail recursion:

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

/* function prototypes */
void reverse(char *string);
void reverseWorker(char *string, int start, int end);

int main(int argc, const char *argv[]) {
  char string[] = "Hello, world.";
  printf("string (original) = %s\n", string);
  /*
  reverse(string);

  Or, to reverse each word in the string...
  */

  char *ptr = strtok(string, " ");
  while(ptr != NULL) {
    reverse(ptr);
    ptr = strtok(NULL, " ");
    if(ptr != NULL)
      *(ptr-1)=' ';
  }

  /* the rest is the same */

  printf("string (reversed) = %s\n", string);
  return 0;
}

void reverse(char *string) {
  reverseWorker(string, 0, strlen(string)-1);
}

void reverseWorker(char *string, int start, int end) {
  /* terminal condition */
  if(start>=end)
    return;
  /* swap */
  char temp = string[start];
  string[start]=string[end];
  string[end]=temp;
  /* recursive step */
  reverseWorker(string,start+1,end-1);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Hi,thank you for your help. but I don't to use a tail recurtion.. just the function I wrote. and just on one word, not a sentence. just for my knowledge, can you explain what's the logic behind were function? the algorth I mean.
Use start and end "pointers" (which, in this case, are indexes into the character array), swap the chars at the start and end locations, and recursively continue by moving start and end closer to each other by one; terminate the recursion when start and end meet. You had the swap correct, but only for a specific start and end.
can you show me what you mean by a code? this is really important to me, and I can't fined anybody who can explain this to me. and also, what would be in the main function ?
So, you have to reverse just one word in the string, or each word individually?
@ Danny Daglas just one word
|
0
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void reversefill(char*const from,char*const to){
    if(from>=to){
        //Nothing to do. Odd lengths get to from==to.
        //Even lengths 'swap over'.
        //Pointer comparison guaranteed legit - in the same array.
        return;
    }
    //Textbook swap.
    //Could use the classic xor swap trick.
    //However that will just confuse in this example.
    const char temp=*from;
    *from=*to;
    *to=temp;

    //Carry on moving our 'work' points closer together from both ends.
    reversefill(from+1,to-1);
}

void reverse(char* str){
    const size_t sz=strlen(str);
    if(sz==0){
        return;//Can't use str-1 - UB.
        //Could head for the door if sz==1 but this is a training example on recursion.
        //So we'll just show it works if from==to.
    }
    reversefill(str,str+sz-1);
}

int main() {
    char*const str="Hello World!";
    char*const rev=malloc(strlen(str)*sizeof(*str));//sizeof not required but good habit

    strcpy(rev,str);

    reverse(rev);

    printf("%s\n",rev);

    free(rev);//Don't listen to smart-arses who say that's unnecessary. 
    //Unless you really need to use the trick...
    //However examples should be the cleanest possible code.

    return EXIT_SUCCESS;
}

I think the requirement was in-place reversal.

The only way to do that (I think the OP realises) is to work from the ends and swap 'symmetric' positions. That is swap the first with last, second with second last, etc.

That's fine but we need to realise when we've 'met' in the middle. That's obvious of odd length cases - the two working points meet. For even cases we need to spot the workings 'crossing over'.

That's exactly how reversefill(,) works.

I think this code is an excellent specimen of the strengths and weaknesses of C strings. The main function is fantastically efficient.

But actually has to scan the string twice because C doesn't intrinsically provide a O(1) way of obtaining the length of a string!

Comments

0

You could write the function like

void reverse( char s[] )
{
    reverse_impl( s, strlen( s ) );
}

void reverse_impl( char s[], size_t n )
{
    if ( !( n < 2 ) )
    {
        char c = s[0];
        s[0] = s[n-1];
        s[n-1] = c;
        reverse_impl( s + 1, n - 2 );
    }
}

But it is a wrong solution because it is not function void reverse( char s[] ); that is a recursive function. It is function void reverse_impl( char s[], size_t n ); that is recursive. But according to your assignment it is function void reverse( char s[] ); that has to be recursive.

So the correct solution is the following.

#include <stdio.h>

void reverse( char s[] )
{
    if ( *s  )
    {
        char *p = s;
        char c;

        do
        {
                    c = *p;
                    *p = *( p + 1 );
                    *( p + 1 ) = c; 
        } while ( *p++ );

        reverse( s );

        c = *p;
        *p = *( p - 1 );
        *( p - 1 ) = c;
    }
}


int main( void ) 
{
    char s[] = "abcde";

    puts( s );
    reverse( s );
    puts( s );

    return 0;
}

The output is

abcde
edcba

This recursive function uses neither standard function :)

5 Comments

Hi, thank you so much, but you used loops with the recurtion... I can't :(
@Tamar Kravitz I think you understand your assignment incorrectly. Do not using loops in your assignment means that the function has to be recursive. But is does not mean that a recursive function may not use within itself a loop. For example the same standard function strlen() is in fact a loop.
I understod it perfectly. I can't use loops.
@Tamar Kravitz You are entirely wrong because you need at least to know the length of the string and without a loop pr function strlen that in turn is a loop you will not find the length of the string.
@Tamar Kravitz The problem is that you simply do not understand the algorithm I suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.