Print reverse of a string using recursion

Write a recursive C function to print reverse of a given string.

Program:

C

// C program to reverse 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);
   }
}

/* Driver program to test above function */
int main()
{
   char a[] = "Geeks for Geeks";
   reverse(a);
   return 0;
}

Python

# Python program to reverse a string using recursion

# Function to print reverse of the passed string
def reverse(string):
	res = ''
	for i in xrange(len(string),0,-1):
		res += string[i-1]
	return res

# Driver program to test above function
string = "Geeks for Geeks"
print reverse(string)

# Following is a single line statement to reverse in python
# print string[::-1]

# This code is contributed by Bhavya Jain


Output:
skeeG rof skeeG


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.

Time Complexity: O(n)

See Reverse a string for other methods to reverse string.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



GATE CS Corner    Company Wise Coding Practice





Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the link here.