This post helps to reverse a string using recursion by the use of C programming language.

C program to Reverse a String Using Recursion

#include <stdio.h>
#include <string.h>
void reverse(char[],int,int);
int main()
{
    char str1[20];
    int size;
    printf("Enter a string to reverse: ");
    scanf("%s",str1);
    size=strlen(str1);
    reverse(str1,0,size-1);
    printf("The string after reversing is: %s", str1);
    return 0;
}
//function is called to reverse the string
void reverse(char str1[], int index, int size)
{
    char temp;
    temp=str1[index];
    str1[index]=str1[size-index];
    str1[size-index]=temp;
    if (index==size/2)
    {
        return;
    }
    reverse(str1,index+1,size);
}

Output

Explanation

In this program, we start by initializing the functions and the variables. The variable str1 with the value of size is initialized to store the string values. Now we get the string character from the user and check the size and length(strlen) of the str1, and then print the result.

void reverse(char[],int,int);
int main()
{
    char str1[20];
    int size;
    printf("Enter a string to reverse: ");
    scanf("%s",str1);
    size=strlen(str1);
    reverse(str1,0,size-1);
    printf("The string after reversing is: %s", str1);
    return 0;
}

Now the function is called for reversing the string character. Here we initialize a variable named temp to check whether the index and the size are equal and divided by 2. It now returns the values of the string. 

//function is called to reverse the string
void reverse(char str1[], int index, int size)
{
    char temp;
    temp=str1[index];
    str1[index]=str1[size-index];
    str1[size-index]=temp;
    if (index==size/2)
    {
        return;
    }
    reverse(str1,index+1,size);
}

The program now returns the string values as reversed.

Leave a Reply

Your email address will not be published. Required fields are marked *

Liked this content?. Please spread the word :)

  • RSS
  • Twitter
    Visit Us
    Follow Me