Program to reverse a string


Consider the following code which reverses a string using for loop:

CODE:

# include <stdio. h>

# include <conio. h>

void main ()

{

   int i, j, k;

   char st [100];

   char rv [100];

   printf (“Enter a string to reverse\t”);

   scanf (“%s”, st);

   printf (“Original string %s”, st);

   for(i = 0; st [i] != ‘\0’; i++);

   {

      k = i-1;

   }

   for(j = 0; j <= i-1; j++)

   {

      rv [j] = st [k];

      k –;

   }

   printf (“Reversed string %s”, rev);

   getch ();

}

OUTPUT:

Enter a string to reverse new

Original string new

Reversed string wen


Program to reverse a string using recursion:

Consider the following example to reverse a string using recursive function:

CODE:

# include <stdio. h>

# include <conio. h>

char* reverse (char *st);

void main ()

{

   int i, j, k;

   char st [100];

   char *rv;

   printf (“Enter a string to reverse\t”);

   scanf (“%s”, st);

   printf (“Original string %s”, st);

   rv = reverse(st);

   printf (“Reversed string %s”, rv);

   getch ();

}

char* reverse (char *st)

{

   static int i=0;

   static char rv [100];

   if (*st)

   {

      reverse (st + 1);

      rv [i ++] = *st;

   }

  return rv;

}

OUTPUT:

Enter a string to reverse new

Original string new

Reversed string wen