Both $ and @ are characters to display, so they should be
'$' and
'@'. If you wish them to be strings, you can do that as well:
"$" and
"@".
Are you sure your question isn't more about how to implement the recursion itself?
Remember, recursion is a way of writing a loop. If I wanted to print a $ five times, I could use a loop:
1 2
|
for (int n = 0; n < 5; n = n+1)
cout << '$';
|
The important piece of information for running the loop is the variable
n
-- without it, the loop would not know when to stop.
Recursion works the same way: you need an additional piece of information to know when to stop. You can do this by making an argument to the function.
1 2 3 4 5 6
|
void print_5_dollar_signs( int n = 0 ) // Same as the loop: start with n = 0
{
if (n == 5) return; // The loop says, while n < 5 continue. Here we say, if !(n < 5), we quit.
cout << '$';
print_5_dollar_signs( n+1 ); // Same as the loop: next n = current n+1
}
|
At this point, you may notice that your function is not very general. What if I wanted to print 7 dollar signs?
We
could just add another argument:
1 2 3 4 5 6
|
void print_x_dollar_signs( int x, int n = 0 )
{
if (n == x) return;
cout << '$';
print_x_dollar_signs( x, n+1 );
}
|
That is not very satisfying, though, because it seems that we have too many arguments in there. You may have already seen the possibility in your own head: why not
count backwards?
Instead of starting at zero and counting
up to 5, why not start at 5 and count
down to zero?
1 2
|
for (int n = 5; n > 0; n = n-1)
cout << '$';
|
Now we only need one argument again:
1 2 3 4 5 6
|
void print_n_dollar_signs( int n = 5 )
{
if (n == 0) return;
cout << '$';
print_n_dollar_signs( n-1 );
}
|
That's a whole lot prettier. And you can use it anywhere:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
using namespace std;
void print_n_dollar_signs( int n )
{
if (n == 0) return;
cout << '$';
print_n_dollar_signs( n-1 );
}
int main()
{
print_n_dollar_signs( 5 );
cout << endl;
print_n_dollar_signs( 7 );
cout << endl;
}
|
The next thing to think about is... what if I want to print something else?
(Hint: add an argument to the function!)
Hope this helps.