Arpit Tomar
Arpit Tomar

Reputation: 175

What's wrong with this recursion program

I'm trying to reverse a string using recursion but it's not working. What's the mistake?.. It's showing some output "tset a ♠♣♦♥☻☺" for test case "this is a test"

#include "stdio.h"
#include "string.h"

void rec(char [],int,int);

void main()
{
  char ch[50];int j,i=0;
  printf("Enter the string: ");
  gets(ch);
  j=strlen(ch)-1;
  rec(ch,i,j);
  puts(ch);
}

void rec(char ch[],int i,int j)
{
  char t;
  if(i>=j)  return;
  t=ch[i];
  ch[i]=ch[j];
  ch[j]=i;
  rec(ch,++i,--j);
}

Upvotes: 0

Views: 66

Answers (3)

haccks
haccks

Reputation: 106012

You need to change

ch[j]=i;  

to

ch[j]= t;   

Note that no need to null terminate the string explicitly. strlen gives th length the string excluding the \0 character. You are passing strlen(ch)-1 to your function it means it will start reversing the characters from the character just before \0. So, after the reversal the string will be null terminated.

Upvotes: 0

Gopi
Gopi

Reputation: 19864

ch[j]=i;

You are assigning an integer to character which is not what you want. You are storing the value in t so

ch[j] = t;

is what you need.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

In this statement

ch[j]=i;

you are using i instead of t

The function could be written simpler with only two parameters. For example

void rec( char s[], size_t n )
{
    if ( !( n < 2 ) )
    {
        char c = s[0];
        s[0] = s[n-1];
        s[n-1] = c;

        rec( s + 1, n - 2 );
    }
}

and called like

rec( ch, strlen( ch ) );

Now try to write the function with only one parameter: char s[]:)

Upvotes: 0

Related Questions