Question #318537

  1. In the code editor, you are provided with a main() function that asks the user for a string and passes this string and the size of this string to a function call of the function, preserveString().
  2. This preserveString() function has the following description:
  3. Return type - void
  4. Name - preserveString
  5. Parameters
  6. The string
  7. Length of the string
  8. Description - this is a recursive function that prints the string repeatedly. Each time it prints the string, it excludes the last character of the string until only one character is left.
  9. This preserveString() function has already been partially implemented. Your only task is to add the recursive case of this function.

Expert's answer

#include <iostream>
#include <string>

using namespace std;

void preserveString(string word, int sz)
{
	while (sz > 0)
	{
		cout << word.substr(0, sz-1) << endl;
		return preserveString(word, sz - 1);
	}
}

int main()
{
	string word;
	cout << "Please, enter a string: ";
	cin >> word;
	preserveString(word, word.size());
}
LATEST TUTORIALS
APPROVED BY CLIENTS