1,105,344 Community Members

Help: Recursion/Arrays

Member Avatar
theoryforlife
Newbie Poster
5 posts since Feb 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hello, I've been working at this code from a couple angles, I've had two people I've known to help me, but even with their help it hasn't worked.
The question I have relates to CodeLab:

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. The function should invoke printStars to accomplish the task of printing a single line.


I've tried:

void printStarBucks (int n){
	printStars(n);
	printBucks(n);
}

void printStars (int n){
	if (n > 0){
		cout << "*";
		printStars (n-1);
	}
}

void printBucks(int n){
	if (n > 0){
		cout << "$";
		printBucks(n-1);
	}
}

As well as:

void printStarBucks(int n){
	if(n>0){
		printStars(N);
	}
}

void printStars (int N){
	cout << "*";
	prtinStarBucks (n-1);
	cout << "$";
}
Member Avatar
rubberman
Senior Poster
3,999 posts since Mar 2010
Reputation Points: 513 [?]
Q&As Helped to Solve: 501 [?]
Skill Endorsements: 87 [?]
 
0
 

The obvious point of this exercise is to learn recursion, which is when a function calls itself, terminating when some barrier is reached. A symbol for this is the great worm Ouroboros who encircles the Earth, eating his tail. An interesting article about this is here: http://en.wikipedia.org/wiki/Ouroboros. The process potentially never ends... :-) Here is an example:

void recurse_until( int stop_when )
{
    if (stop_when > 0)
    {
        recurse_until( stop_when - 1 );
    }
    return;
}

So, recurse_until() will keep calling itself until stop_when (the barrier) == 0, then then entire thing pops back to the original caller. This is, coincidentally enough (back to Ouroboros) called tail recursion.

If you do something like this, and each call where the barrier is > 0 you output a '*' before you call recurse_until() again, and a '$' after the call, you will get the results you want, with a single call from main() to recurse_until(), using the input number for the initial barrier value.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: