Answer to Question #323272 in C++ for Magisk

Question #323272
  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 already been partially implemented. Your only task is to add the recursive case of this function.

To do: Print the string repeatedly, each time it prints the string, exclude the last letter until only 1 letter is left.


Given code:

#include <iostream>

#include <cstring>

using namespace std;


#define STR_MAX_SIZE 100


void preserveString(char*, int);


int main(void) {

  char str[STR_MAX_SIZE];


  cout << "Enter string: ";

  fgets(str, STR_MAX_SIZE, stdin);


  preserveString(str, strlen(str));


  return 0;

}


void preserveString(char *str, int size) {

  if(size > 0) {

    for(int i = 0; i < size - 1; i++) {

      cout << str[i];

    }

    cout << endl;


    // TODO: Add the recursive case of the function here

  }

}



1
Expert's answer
2022-04-04T07:48:06-0400
#include <iostream>
#include <cstring>

using namespace std;


#define STR_MAX_SIZE 100

void preserveString(char*, int);

int main(void)
{
	char str[STR_MAX_SIZE];
	cout << "Enter string: ";
	fgets(str, STR_MAX_SIZE, stdin);
	preserveString(str, strlen(str));
	return 0;
}

void preserveString(char *str, int size)
{
	if (size > 0)
	{
		for (int i = 0; i < size - 1; i++)
		{
			cout << str[i];
		}
		cout << endl;
		preserveString(str, size - 1);
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS