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;
}