Wednesday 27 February 2013

Recursion to reverse a string




/*  C program to Reverse a string using Recursion  */



# include <stdio.h>
# include <string.h>
void revFunc(char*,int,int); // function declaration/prototype

void main()
{
   char str[25];
   int len;
   printf("www.techterabyte.com");
   printf("\nEnter string: ");

   // for reading string from stdin
   gets(str);

   // calculating length of string
   len = strlen(str);
   revFunc(str,0,len -1);
   printf("String after reversing:");
   printf("%s\n",str);
   getch();
}

void revFunc(char *x, int start, int end)
{
    char a,b,c;
    if(start >= end)
       return;

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

    // recursive call
    revFunc(x,++start,--end);
}




Output

www.techterabyte.com
Enter string: blog belongs to AMIT
String after reversing:TIMA ot sgnoleb golb




No comments:

Post a Comment