Search This Blog

Translate This Page

Friday, 13 September 2013

Print Reverse of a string using Recursion


Print reverse of a  string using recursion:


# include <stdio.h>

/* Function to print reverse of the passed string */
void reverse(char *str)
{
   if(*str)
   {
       reverse(str+1);
       printf("%c", *str);
   }
}

int main() 
{
   char a[] = "Tech Stuff for Interview";
   reverse(a);
   return 0;
}

Explanation:
 Recursive function (reverse) takes string pointer (str) as input and calls itself with next location to passed pointer (str+1). Recursion continues this way, when pointer reaches ‘\0′, all functions accumulated in stack print char at passed location (str) and return one by one.


1 comment:

  1. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
    website: geeksforgeeks.org

    ReplyDelete

Latest Current Visitor

World Clock Time, for View Click on Country