C program to reverse a string using recursion

Here, we are going to learn how to reverse a string using recursion in C programming language?
Submitted by Nidhi, on July 17, 2021

Problem Solution:

Read a string and then reverse a string using recursion.

Program:

The source code to reverse a string using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to reverse a string using recursion

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

void StrRev(char str[], int i, int len)
{
    char t;
    int j;

    j = len - i;

    t = str[i];
    str[i] = str[j];
    str[j] = t;

    if (i == len / 2)
        return;

    StrRev(str, i + 1, len);
}

int main()
{
    char str[20];
    int len = 0;

    printf("Enter a string: ");
    scanf("%[^\n]s", str);

    len = strlen(str);
    StrRev(str, 0, len - 1);

    printf("Reversed string is: %s\n", str);

    return 0;
}

Output:

RUN 1:
Enter a string: Yahoo!
Reversed string is: !oohaY

RUN 2:
Enter a string: Google
Reversed string is: elgooG

RUN 3:
Enter a string: Hello, world!
Reversed string is: !dlrow ,olleH

Explanation:

In the above program, we created two functions StrRev() and main() function. The StrRev() is a recursive function, here we reversed the specified string.

In the main() function, we created a string str and read the value of str from the user. Then we called StrRev() recursive function to reverse the string and printed the result on the console screen.

C String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.