Question

Write a recursive function that takes a string as an input and returns the reverse of...

Write a recursive function that takes a string as an input and returns the reverse of the string.

Write a recursive function rec_string that produces the output shown below for the corresponding function calls. Write a main function to test the function.

Method call rec_string(‘abcde’), will produce the following output:

*

e

de

cde

bcde

abcde

Method call rec_string(‘abc’), will produce the following output:

*

c

bc

abc

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have written the program in c++

Question 1:

Here is code:

string rec_string(string str){
if (str.length() == 1) {
return str;
}else{
return reverseStringRecursively(str.substr(1,str.length())) + str.at(0);
}
}

Question 2:

Here is function:

void rec_string(string str){
static int count = 0;
if(count == 0) // if count is 0 prints only *
cout << "*" << endl;
   else
   {
       // loops from str length - count to str end
   for(int i = str.length() - count; i < str.length() ; i++)
   cout << str[i];
cout << endl;
}
if(count == str.length()) // if count read str length then exit
return;
count++;
rec_string(str);
}

Sample main function to test:

#include <iostream>
#include <string>
using namespace std;

void rec_string(string str){
static int count = 0;
if(count == 0) // if count is 0 prints only *
cout << "*" << endl;
   else
   {
       // loops from str length - count to str end
   for(int i = str.length() - count; i < str.length() ; i++)
   cout << str[i];
cout << endl;
}
if(count == str.length()) // if count read str length then exit
return;
count++;
rec_string(str);
}
int main()
{
rec_string("abcde");
return 0;
}

Output:

dle cde bcde abcdle

Add a comment
Answer #2
#include<stdio.h>
void revs(char *p)
{
    if(*p)
    revs(p+1);
    printf("%c",*p);
}
int main()
{
    char name[40];
    scanf("%[^\n]s",name);
    revs(name);
}


source: c
answered by: lol
Add a comment
Know the answer?
Add Answer to:
Write a recursive function that takes a string as an input and returns the reverse of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT