Write a recursive C function to print reverse of a given string.
Program:
Program:
- C
- Python
// 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; } |
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.
No comments:
Post a Comment