Print reverse of a string using recursion

Write a recursive C function to print reverse of a given string.

Program:

# include <stdio.h>

/* Function to print reverse of the passed string */
void reverse(char *str)
{
   if(*str)
   {
       reverse(str+1);
       printf("%c", *str);
   }
}

/* Driver program to test above function */
int main()
{
   char a[] = "Geeks for Geeks";
   reverse(a);
   getchar();
   return 0;
}


Explanation:
Recursive function (reverse) takes string pointer (str) as input and calls itself with next location to passed pointer (str+1). Recursion continues this way, when pointer reaches ‘\0′, all functions accumulated in stack print char at passed location (str) and return one by one.

Time Complexity: O(n)





  • Marsha Donna

    program to reverse string using recursion see the link:
    http://ideone.com/UZZQFr

  • Govinda

    #include
    void reverse(char *,int ,int ,char);
    int strlen(char *);
    /—————————————————————–
    int main()
    {
    char temp;
    char str[] = “geekforseek”;
    reverse(str, 0, strlen(str) – 1, temp);
    printf(“%sn”,str);
    return 0;
    }
    ————————————————————————–
    void reverse(char *str,int i, int len, char temp)
    {
    if(i >= len)
    return;
    else{
    temp = *(str+i);
    *(str + i) = *(str + len);
    *(str + len) = temp;
    }
    reverse(str , i+1, len-1, temp);
    }
    ——————————————————————————
    int strlen(char *str)
    {
    return (*str ? (1 + strlen(++str)) : 0);
    }

    ———————————————————————————-

  • Amar

    Code:

    #include

    #include

    #include

    #include

    void Reverse1 (char *str, int strlen)

    {

    static int i=1;

    char temp;

    if(*str)

    {

    Reverse1((str+1),strlen);

    if (i=2);

    strcpy (str,argv[1]);

    Reverse1 (str,strlen(str));

    printf (“Input String is %s,
    Reversed String is %s”,argv[1],str);

    printf (“n”);

    return 0;

    }

    Output:

    ./a.out A

    Input String is A, Reversed String is
    A

    ./a.out AB

    Input String is AB, Reversed String is
    BA

    ./a.out ABC

    Input String is ABC, Reversed String is
    CBA

    ./a.out ABCD

    Input String is ABCD, Reversed String
    is DCBA

    • Amar

      Moderator kindly delete this post… its getting posted incorrectly…

  • Amar

    Code:
    #include
    #include
    #include
    #include
    void Reverse1 (char *str, int strlen)
    {
    static int i=1;
    char temp;
    if(*str)
    {
    Reverse1((str+1),strlen);
    if (i=2);
    strcpy (str,argv[1]);
    Reverse1 (str,strlen(str));
    printf (“Input String is %s, Reversed String is %s”,argv[1],str);
    printf (“n”);
    return 0;
    }

    Output:

    ./a.out A
    Input String is A, Reversed String is A

    ./a.out AB
    Input String is AB, Reversed String is BA

    ./a.out ABC
    Input String is ABC, Reversed String is CBA

    ./a.out ABCD
    Input String is ABCD, Reversed String is DCBA

    • Amar

      Not sure why Main function & Reverse1 function are getting displayed incorrectly :(

  • Amar

    #include
    #include
    #include
    #include

    void Reverse1 (char *str, int strlen)
    {
    static int i=1;
    char temp;
    if(*str)
    {
    Reverse1((str+1),strlen);
    if (i=2);
    strcpy (str,argv[1]);
    Reverse1 (str,strlen(str));
    printf (“Input String is %s, Reversed String is %s”,argv[1],str);
    printf (“n”);
    return 0;
    }

    Output:
    ./a.out A
    Input String is A, Reversed String is A

    ./a.out AB
    Input String is AB, Reversed String is BA

    ./a.out ABC
    Input String is ABC, Reversed String is CBA

    ./a.out ABCD
    Input String is ABCD, Reversed String is DCBA

  • Anushka

    Hi,
    in case we change the above code, where the user has to enter the size of an array and then an array of characters. then reverse that array using recursion. how do we do it? can somebody please help.

    • raju

      Hi, I have written requested code in c++ syntax.

      int main() {
      int n;
      cout<>n;

      char a[n+1] ;

      cout<>a;

      reverse(a);
      }

  • Guest

    str=”

  • abhishek08aug
     
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #define NO_OF_CHARS 256
     
    void print_reverse_recurse(char * str) {
      if(*str=='\0') {
        return;
      } else {
        print_reverse_recurse(str+1);
        printf("%c", *str);
      } 
    }
     
    int main() {
      char * str="Geeks for geeks";
      print_reverse_recurse(str);
      return 0;
    }
     

    skeeg rof skeeG

  • coderAce

    The present implementation as such doesn’t pose any difficulty at all. It is simply printing out the string in reversed order, but then again, that was the question :)

    Anyways, if anyone is interested in reversing the string in place by recurion, here is the code:

    void reverse_str(char *s)
    {
    static int i=strlen(s)-1;

    if(*s)
    {
    reverse_str(s+1);
    if(i>0)
    {
    char temp=*(s-i);
    *(s-i)=*(s);
    *(s)=temp;
    i=i-2;
    }
    }
    }

    Input:{“siht ekil skool desreveR”}
    Output:Reversed looks like this

    Watch out for the following tricks:
    (1)I am doing *(s-i) to tap into the leftmost character to swap.
    (2)The rightmost character to be swapped is always *(s)
    (3)I am doing i=i-2. This is because, once the program returns from one recursive call, s also gets decremented by 1( we are passing reverse_str(s+1)). So if we simply do a i– and subtract from s we will point to the previous character of the leftmost character to be swapped.

    • Amar

      I am getting the following error: “error: initializer element is not constant” for the statement “static int i=strlen(s)-1;”

      • Marsha Donna

        same error here..upon removing the stsatic keyword..the output is not correct

  • datta

    /*The C program to reverse a string using recursion without swapping and extra space*/

    #include”stdio.h”
    #include”malloc.h”
    #include”string.h”

    void rev(char *str,char ch,int index);

    int main()
    {
    char *str;
    str = malloc(sizeof(char *));

    scanf(“%s”,str);

    rev(str,*(str+strlen(str)-1),strlen(str)-1);

    printf(“The reversed string is %s\n”,str);

    return 0;
    }

    void rev(char *str,char ch,int index)
    {

    if(index < 0)
    return;
    else{
    rev(str,*(str+index-1),index-1);
    str[strlen(str)-1-index] = ch;

    }
    }

  • joker

    #include
    using namespace std;
    void print_rev(char *s)
    { if(*s==”) return;
    print_rev(s+1);
    printf(“%c”,*s);
    }
    main()
    { char s[100];
    cin>>s;
    print_rev(s);
    system(“pause”);
    }

  • Mayank Verma

    A simple program

       1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 char *reverseStringRecursive(char *input, char *output);
      6 
      7 int main() {
      8     char input[100] = "Geeks for Geeks.";
      9     char output[100] = {0};
     10 
     11     reverseStringRecursive(input, output);
     12     printf("String is:%s\n", input);
     13     printf("String Reversed:%s\n", output);
     14     return (1);
     15 }
     16 
     17 char *reverseStringRecursive(char *input, char *output) {
     18     static int i = 0;
     19     if (*input) {
     20         reverseStringRecursive(input + 1, output);
     21         output[i] = *input;
     22         i++;
     23     }
     24     return (input);
     25 }
    
     

    output:

    String is:Geeks for Geeks.
    String Reversed:.skeeG rof skeeG

  • gvdfg

    void reverse(char *str)
    {
    static int i=0;
    if(*str){
    reverse(str+1);
    str[i] = *str;
    i++;
    }
    }

    /* Driver program to test above function */
    int main()
    {
    char a[] = “Geeks for Geeks”;
    reverse(a);
    printf(“%s”, a);
    getchar();
    return 0;
    }

  • Venky
     
    int my_strlen(char *s) { 
    	char *p=s; 
    	while(*p!='\0') 
    		p++; 
    	return(p-s); 
    }
    void reverse(int pos,char *str) {
    	int len;
    	len	=	my_strlen(str);
    	if(pos<(len/2)) { 
    		char ch; 
    		// Swap str[pos] and str[strlen(str)-pos-1] 
    		ch = str[pos]; 
    		str[pos]=str[len-pos-1]; 
    		str[len-pos-1]=ch; 
    		// Now recurse! 
    		reverse(pos+1,str); 
    	} 
    }
    
    /* Driver program to test above function */
    int main()
    {
       char a[] = "Geeks for Geeks";
       reverse(0,a);
       printf("%s", a);
       getchar();
       return 0;
    }
     
    • coder

      y call strlen in each recursive call of function make it static

  • Ritesh
     
    
    void rev( char *s )
    {
    	if( ( *( s + 1 ) ) )
    		rev( s + 1 );
    	printf( "%c", *s );
    }
    
    int main()
    {
    	char s[100];
    	scanf( "%s", s );
    	rev( s );
    	return 0;
    }
     
  • Ritesh
     void rev( char *s )
    {
    	if( ( *( s + 1 ) ) )
    		rev( s + 1 );
    	printf( "%c", *s );
    }
    
    int main()
    {
    	char s[100];
    	scanf( "%s", s );
    	rev( s );
    	return 0;
    }
     
  • http://wemeanourthoughts.blogspot.com/ Venki

    A similar sort of question given in Programming with C by Byron Gottfred

  • pooja

    There’s one slight problem in this function. The first character will not be printed. So, to resolve the issue, one needs to include the following after call to reverse in the main function.

     
    printf("%c",*a);
     
    • Shekhu

      The code given above works fine for me, it prints “skeeG rof skeeG”. The first character of the reversed string is ”, so it should not be printed. Please correct me if I am wrong.

    • pooja

      my bad. I had written my function by preincrementing the variable and not explicitly adding 1 to it.

      • coder

        gud

         
        /* Paste your code here (You may delete these lines if not writing code) */
         
  • Venki

    Friends, what would be disadvantages of the recursive string reversal method? I guess it won’t be reentrant and not thread safe. Am I correct?

    What are efficient methods of string reversal?

  • divyaC
     
    reverse(char *str){
    	static i=0
    	if(str){
    		reverse(str+1)
    		str[i]=*str;
    		i++;
    	}
    }
     
    • kartik

      The function doesn’t seem to work. Try below program for example.

       void reverse(char *str)
      {
          static int i=0;
          if(*str){
              reverse(str+1);
              str[i] = *str;
              i++;
          }
      }
      
      /* Driver program to test above function */
      int main()
      {
         char a[] = "Geeks for Geeks";
         reverse(a);
         printf("%s", a);
         getchar();
         return 0;
      }
       

      Let me know if I missed something.

      • Guest

        To find the length using RECURSION

        # include
        int lengthcount(char *str)
        {
        static int length=0;
        if(*str!= ”)
        {
        lengthcount(++str);
        length++;
        }
        else
        return length;

        }

        int main()
        { int l;
        char a[] = “ABC”;
        l=lengthcount(a);
        printf(“%d”,l);

        }