### C++ Recursive function "asterisks"

How do I get an output something like this?
Ex.
Input: 5
Output:
* * * * *
* * * *
* * *
* *
*

Here is my code.

</code>

#include <iostream>
using namespace std;

void ASTERISK();

int main()
{

ASTERISK();
return 0;
}

void ASTERISK()
{
int number;
int row, column;

cout << "Enter a number: ";
cin >> number;

row = 1;
while (row<=number)
{
column = 1;
while (column <= number)
{
if (column<=(number-row))
{
cout << " ";
}
else
{
cout << "*";
}
column=column+1;
}
cout <<"\n";
row=row+1;
}
ASTERISK();
}

</code>
Last edited on
Ask for input in main, then pass the int entered as a parameter to the Asterisk function.

When n is passed into Asterisk(n), Asterisk(n) recursively calls Asterisk(n-1) after drawing a single row of asterisks.

The other important thing in recursion is a base case. In this case, it would be when n == 0, you're done making the triangle.

 ``1234567891011121314`` ``````void Asterisk(int n) { if (n <= 0) { return; // base case (you don't need two branches, but just for clarity) } else { // draw single row // ... Asterisk(n - 1); // recursively draw the remaining rows. } }``````
Last edited on
The function doesn't need to be recursive, a couple of loops would handle the logic:
 ``12345678910111213141516171819202122232425`` ``````#include void Asterisk(int); int main() { std::cout << "Number of rows: "; int num_rows { }; std::cin >> num_rows; std::cout << '\n'; Asterisk(num_rows); } void Asterisk(int num_rows) { for (int row { num_rows }; row > 0; --row) { for (int itr { }; itr < row; ++itr) { std::cout << "* "; } std::cout << '\n'; } }``````
 ``1234567891011121314151617181920`` ``````#include using namespace std; void line( int n ) { cout << ( n ? "* " : "\n" ); if ( n ) line( n - 1 ); } void asterisk( int n ) { if ( n ) line( n ), asterisk( n - 1 ); } int main() { int n; cout << "Number of rows: "; cin >> n; asterisk( n ); }``````
Its probably the assignment point, to do it recursively.
it can probably condense even more than this but..
string s(num_rows, '*');
while(s.length())
{
cout << s << endl;
s.pop_back();
}
I don't doubt the assignment is to use recursion, but I was bored and mashed together some simple, crude code to do iteration instead.
Topic archived. No new replies allowed.