BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C program to Reverse a String using recursion

By Chaitanya Singh | Filed Under: C Programs

Here we have defined a function reverse_string, this function calls itself recursively.

#include <stdio.h>
#include <string.h>
void reverse_string(char*, int, int);

int main()
{
    //This array would hold the string upto 150 char
    char string_array[150];
    printf("Enter any string:");
    scanf("%s", &string_array);
 
    //Calling our user defined function
    reverse_string(string_array, 0, strlen(string_array)-1);
    printf("\nReversed String is: %s",string_array);
 
    return 0;
}
 
void reverse_string(char *x, int start, int end)
{
    char ch;
    if (start >= end)
       return;
 
    ch = *(x+start);
    *(x+start) = *(x+end);
    *(x+end) = ch;
 
    //Function calling itself: Recursion
    reverse_string(x, ++start, --end);
}

Output:

Enter any string: chaitanya
Reversed String is: aynatiahc

Comments

  1. Gabriel says

    June 18, 2016 at 1:44 AM

    Hi I think it should be:
    scanf (“%s”, string_array);

    Because the string is already an address (&), right?

    Reply

Leave a Reply Cancel reply

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

Programs

  • C Programs
  • Java Programs
  • C++ Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap