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

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.

for people that are coming later here is a solution that might help, you take this:

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

and make it:

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

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

the reason is that you have to declare the function before using it. i tried it in codelab and it worked.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.