Hatena::Groupcprogramming

C Study Diary

2008-12-22

c4ex13_reverse_recursive.cpp

17:30

Write a recursive version of the function reverse(s) , which reverses the string s in place.

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

#define MAX 500
 
/* reverse string */ 
void reverse(char *s, int sindex, int eindex){
	char temp;
	if(sindex==eindex) {
		return;
	}
	else {
		temp=s[sindex];
		s[sindex]=s[eindex];
		s[eindex]=temp;
		reverse(s,sindex+1,eindex-1);		
	}
}

int main(void){

	char test_str[MAX];
	
	printf("Input string to reverse: \n");
	gets(test_str);
	printf("Test string is : %s\n",test_str);
	reverse(test_str, 0, strlen(test_str)-1);
	printf("After reverse:%s\n",test_str);
	
	return 0;
}

Run:

$ ./c4ex13_reverse_recursive.exe
Input string to reverse:
this is the test string for reverse
Test string is : this is the test string for reverse
After reverse:esrever rof gnirts tset eht si siht