Programming & Design
Question:
Recursive function to reverse order of string?
2012-04-05 04:38:13 UTC
i have to write a recursive program that allows you to enter a word and then output the string in reverse order. I just am unsure of how to reverse the string ??
Three answers:
Priyanka
2012-04-05 04:54:11 UTC
include
#include
void reverse(char **s, int start, int last)
{
char tmp;
if (start >= last)
return;
char *s2 = *s;
tmp = s2[start];
s2[start] = s2[last];
s2[last] = tmp;
reverse(s, start + 1, last - 1);
}
int main()
{
char *s = strdup("Hello World");
printf("%s\n", s);
reverse(&s, 0, strlen(s) - 1);
printf("%s\n", s);
}
2012-04-05 06:40:21 UTC
#include
static void rprint(const char *s);
int main(void)
{
char s[] = "\?smargorp laivirt hcus gnitirw elbuort evah uoy od yhW";
rprint(s);
return 0;
}
static void _rprint(const char *s)
{
if (!*s)
return;
_rprint(s + 1);
putchar(*s);
}
void rprint(const char *s)
{
_rprint(s);
putchar('\n');
}
EDIT: I didn't notice the "enter a word" part. Either way, it's pretty similar to printing a string.
#include
static int revecho(FILE *dstream, FILE *sstream);
int main(void)
{
return revecho(stdout, stdin) ? 0 : main();
}
static int eol(int c, FILE *stream)
{
if (c == '\n')
return 1;
if (c == '\r') {
if ((c = getc(stream)) != '\n')
ungetc(c, stream);
return 1;
}
return 0;
}
static int _revecho(FILE *dstream, FILE *sstream)
{
int c = getc(sstream);
int r = c == EOF;
if (eol(c, sstream) || r)
return r;
r = _revecho(dstream, sstream);
putc(c, dstream);
return r;
}
int revecho(FILE *dstream, FILE *sstream)
{
int r = _revecho(dstream, sstream);
putc('\n', dstream);
return r;
}
James Bond
2012-04-05 05:23:51 UTC
include
#include
void cswap(char *a, char *b)
{
char T=*a;
*a=*b;
*b=T;
}
void rever(char x[], int beg, int end)
{
if(beg
{
cswap(&x[beg],&x[end]);
return(rever(x,beg+1,end-1));
}
}
int main()
{
char str[]="Ramana";
rever(str,0,5);
printf("%s\n", str);
system("PAUSE");
return 0;
}
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...