11.5k views
3 votes
C++ please

Write a recursive function that takes a string parameter and prints the string in reverse order changing every lower case letter to upper case and every upper case letter to lower.

Rewrite your solution to the first solution above so that it returns the reversed string rather than printing it. Input the string in main, pass it to the function, and have main() print the value returned. You may not use any functions you don’t write to solve this problem, other than standard string manipulation functions. this a 2 part question, if anyone could help with both of these it would be greatly appreciated.

User Mothupally
by
7.5k points

1 Answer

4 votes

Final answer:

Two recursive functions in C++ are provided: The first reverses a string while swapping case and prints it, and the second does the same but returns the string. These functions do not rely on any non-standard string manipulation tool and demonstrate clear use of recursion.

Step-by-step explanation:

The requested task is to write two recursive functions in C++ that manipulate a string. The first function should reverse the string and swap the case of each character, printing this result. The second function should also reverse the string and swap the case of each character, but instead of printing the result, it should return the modified string to be printed by main() function.

the

Part 1: Recursive function to print the string

To write this function, you will need to implement a recursive approach that handles one character at a time. The base case for the recursion will be when the string is empty; then you will start unwinding the recursion stack, printing each character with the case swapped:

void printReverseSwapCase(const string& str) {
if (str.empty()) return;
char c = str[0];
if (islower(c)) c = toupper(c);
else if (isupper(c)) c = tolower(c);
printReverseSwapCase(str.substr(1));
cout << c;
}

Part 2: Recursive function to return the string

For the second part, the recursive function will build the result string instead of printing it. When the recursion unwinds, each call will append its character to the result returned by the subsequent call:

string reverseSwapCase(const string& str) {
if (str.empty()) return "";
char c = str[0];
if (islower(c)) c = toupper(c);
else if (isupper(c)) c = tolower(c);
return reverseSwapCase(str.substr(1)) + c;
}

In the main() function, you would call the second function with the user's input string and print the returned value:

int main() {
string input;
cout << "Enter a string: ";
cin >> input;
string reversed = reverseSwapCase(input);
cout << reversed << endl;
return 0;
}

User ChadBDot
by
8.3k points