C program to reverse a string

For example if a user enters a string “crazyforcode” then on reversing the string will be “edocrofyzarc “. We show you two different methods to reverse string the first one we make our own function to reverse string using pointers and in second, reverse string using recursion.

#include<stdio.h>

int string_length(char*);
void reverse(char*);

int main()
{
   char string[100];

   printf("Enter a string\n");
   gets(string);

   reverse(string);

   printf("Reverse of entered string is \"%s\".\n", string);

   return 0;
}

void reverse(char *string)
{
   int length, i;
   char *begin, *end, temp;

   length = string_length(string);

   begin = string;
   end = string;

   for ( i = 0 ; i < ( length - 1 ) ; i++ )
      end++;
// swap the chars till half of the length of the string 
//begin with the end char and so on
   for ( i = 0 ; i < length/2 ; i++ )
   {
      temp = *end;
      *end = *begin;
      *begin = temp;

      begin++;
      end--;
   }
}

int string_length(char *ptr)
{
   int len = 0;

   while( *(ptr+len) != '\0' )
      len++;

   return len;
}

Method 2 : Using recursion

void reverse(char *x, int beg, int end)
{
   char c;

   if (beg >= end)
      return;

   c = *(x+beg);
   *(x+beg) = *(x+end);
   *(x+end)   = c;

   reverse(x, ++begin, --end);
}

In recursion method we swap characters at the begin and at the end and then move towards the middle of the string. This method is inefficient due to repeated function calls and extra space used due to recursion.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation