Question: Write a program in C to reverse a string using recursion
Input: Hello Everyone
Output: enoyrevE olleH
We will use the simple concept of recursion to print the string in reversed order. Note that, we will not store the reversed string in any variable, we are just printing the string in reversed order.
#include<stdio.h> //defining a function to print a string in reverse order void reversePrint(char *str) { // this is the terminating condition of the recursive loop. while(*str != '\0') { // here is the recursive step, // we call the string with its next character. reversePrint(str+1); // once all the recursions are complete, // the program returns here and starts printing the // characters one by one printf("%c",str); } } int main(void) { char *s=(char *)malloc(sizeof(char)*100); //we use this statement so that spaces are scanned scanf("%[^\n]s",s); reversePrint(s); return 0; }
Recursive function (reversePrint) 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.
Method 2:- Reverse a string without using recursion.