This is one of the few times where recursion actually makes perfect sense.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
void PrintAstrix(int n) {
if (n > 0) {
for (int i = 0; i < n; i++)
cout << '*';
cout << endl;
PrintAstrix(n-1);
}
}
int main() {
PrintAstrix(9);
return 0;
}
|
If you are doing this for school you should take the time to understand what is happening here. As long as the initial number of asterisks is > 0 than I will print out that number and than call the function again to print 1 less until n becomes 0 and then the recursion stops since the if statement is not satisfied.
If that if statement was not there the recursion would never stop. You must always have a base case that happens at some point or the loop will never end.
So if you replaced the 9 with 0 it would print nothing but if you changed it to 50 it would look like this.
**************************************************
*************************************************
************************************************
***********************************************
**********************************************
*********************************************
********************************************
*******************************************
******************************************
*****************************************
****************************************
***************************************
**************************************
*************************************
************************************
***********************************
**********************************
*********************************
********************************
*******************************
******************************
*****************************
****************************
***************************
**************************
*************************
************************
***********************
**********************
*********************
********************
*******************
******************
*****************
****************
***************
**************
*************
************
***********
**********
*********
********
*******
******
*****
****
***
**
*