C Program to find the reverse of a String using recursion

In this C Programming example, we will implement the program to find the reverse of a String using recursion and print the output on the console.

1. Reverse of a String using recursion

To reverse a string using recursion, we swap the characters from the beginning of the string with the last character, the second character with the second last, and so on until all the values are swapped once i.e. till we reach the middle of the string.

Example: 
Input: hello world
Output: dlrow olleh

Helpful topics to understand this program better are-


2. C Program to reverse a string using recursion

Let’s discuss the execution(kind of pseudocode) for the program to find the reverse of a string using recursion in C.

  1. Initially, the program will prompt the user to enter a string.
  2. Here, gets(input) will hold the string entered by the user and passes the string in the reverse(char *input, int begin, int end) function and then a recursive call reverse is made.
  3. Here, in the reverse(char *input, int begin, int end) function, the nth value from the beginning is swapped with the nth value from the end till we reach the middle of the string.
  4. Now, all the characters are reversed and then printed on the console.

Let us now implement the above execution of the program to find the reverse of a string using recursion in C.

#include <stdio.h>
#include <string.h>

void reverse(char *input, int begin, int end) {
  char temp;

  if (begin >= end)
    return;

  temp = *(input + begin);
  *(input + begin) = *(input + end);
  *(input + end) = temp;

  reverse(input, ++begin, --end);
}

int main() {
  char input[100];
  printf("Enter the string or characters -> ");
  gets(input);
  reverse(input, 0, strlen(input) - 1);
  printf("Reversed string -> %s", input);
  return 0;
}

Note: In the above program the characters must be entered under the declared range char[100].

Output
Enter the string or characters -> Codingeek
Reversed string -> keegnidoC

3. Conclusion

In this C Programming example, we have discussed how to find the reverse of a string using recursion in C.


Helpful Links

Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.

Also for the example C programs please refer to C Programming Examples.

All examples are hosted on Github.


Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index