Open In App

C Program to Reverse a String Using Recursion

Last Updated : 15 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Reversing a string means changing the order of characters in the string so that the last character becomes the first character of the string. In this article, we will learn how to reverse a string using recursion in a C program.

The string can be reversed by using two pointers: one at the start and one at the end. Swap the values of these two pointers while moving the pointers towards each other. Let’s take a look at an example:

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

// Function to reverse string using recursion
void revRecursive(char *l, char *r) {
  
  	// Till two pointers do not meet, 
 	// swap the values they point to
    if (l != r) {
        char c = *l;
        *l = *r;
        *r = c;
      
      	// Recursive call
        revRecursive(l + 1, r - 1);
    }
}

// Wrapper function
void rev(char *s) {

    // Calling the recursive function
    revRecursive(s, s + strlen(s) - 1);
}

int main() {
    char s[] = "GeeksforGeeks";

    // Reversing the string s
    rev(s);

    printf("%s", s);
    return 0;
}

Output
skeeGrofskeeG


Next Article

Similar Reads