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

c4ex11_itoa_recursive.cpp

17:30

Adapt the ideas of printd to write a recursive version of itoa ; that is, convert an integer into a string by calling a recursive routine.

Question: it may not be very smart to use an external variable as the string index, but I cannot think of a better way in the recursive routine. Suggestion welcomed!

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

#define MAX 20
 
int i;  /* string index */

/* put char to string */ 
void sputchar(char c, char* s){
	
	s[i++]=c;
	s[i]='\0';
}
 
void itoa(long n, char* s){
	
	i=0;
	if(n<0) {
		sputchar('-',s);
		n=-n;
	}	
	if(n/10==0) {
		sputchar(n%10+'0',s);
	}else{
		itoa(n/10,s);
		sputchar(n%10+'0',s);
	}
	
}

int main(void){

	long a = -1122333;
	char *buff;
	
	itoa(a, buff);
	printf("itoa(%d)=%s\n",a,buff);
	a =890556;
	itoa(a, buff);
	printf("itoa(%d)=%s\n",a,buff);

	return 0;
}

Run:

$ ./c4ex11_itoa_recursive.exe
itoa(-1122333)=1122333
itoa(890556)=890556

ゲスト



トラックバック - http://cprogramming.g.hatena.ne.jp/annancy/20081222