Hello I\'m stuck on these two recursion question. (1)Write the definition of a f
ID: 651228 • Letter: H
Question
Hello I'm stuck on these two recursion question.
(1)Write the definition of a function named printStarBucks that receives a non-negative integer n and prints a line consisting of N asterisks followed by N dollars signs. So, if the function received 5 it would print:
*****$$$$$
and if received 3 it would print ***$$$
The function must not use a loop of any kind (for, while, do-while) to accomplish its job.
(2)
Write a recursive, string -valued function, replace, that accepts a string and returns a new string consisting of the original string with each blank replaced with an asterisk (*)
Replacing the blanks in a string involves: Nothing if the string is empty
Otherwise:
If the first character is not a blank, simply concatenate it with the result of replacing the rest of the string
If the first character IS a blank, concatenate an * with the result of replacing the rest of the string
Explanation / Answer
1)
//C ++ program that prints stars and dollars using
//the function void printStarBucks recursively for
//value n
#include<iostream>
using namespace std;
void printStarBucks(int number);
int main()
{
int n=5;
cout<<"n-value "<<n<<endl;
printStarBucks(n);
n=3;
cout<<" n-value "<<n<<endl;
printStarBucks(n);
system("pause");
return 0;
}
//The recursive function printStarBucks that takes a integer value
//and prints starts followed by dollas symbols
void printStarBucks(int n)
{
//check if n is greater than zero
//then print start and call the method recursively
if(n>0)
{
cout << "*";
//calling recursively by decrementing the n value by one
printStarBucks(n-1);
//print dollar sign
cout << "$";
}
}
//Explantion :
//Functions use stacks
//This functions first place "*" and calls the method printStarBucks(n-1);
//printStarBucks(n-1) calls the same method then prints "*"(Previous)"*"(current)="**" and calls the method printStarBucks(n-2);
//printStarBucks(n-2) calls the same method then prints "**"(Previous)"*"(current)="***" and calls the method printStarBucks(n-3);
//printStarBucks(n-3) calls the same method then prints "***"(Previous)"*"(current)="****" and calls the method printStarBucks(n-4);
//Until the value n is greater than zero or equal to one,1.
//Now for each call there is a dollar symbol in each stack then prints when the n -value less than zero
sample output:
n-value 5
*****$$$$$
n-value 3
***$$$Press any key to continue . . .
Hope this could helps you..
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.