How do I write a recursive function in C++ to display a triangle of* like this:
ID: 3615215 • Letter: H
Question
How do I write a recursive function in C++ to display a triangle of* like this:*
**
***
****
****
I am able to write a recursive function to display an inverted triangle like this:
***
**
*
The code for the inverted triangle function is:
- void inverted(int a)
- {
- if (a==1)
- {
- cout<<"*"<<endl;
- }
- else
- {
- for (int i=0; i<a; i++)
- {
- cout<<"*";
- }
- cout<<endl;
- inverted(a-1);
- }
- }
I am allowed to use a loop (e.g. for loop) to print a row of * but I must use*
a recursive function to control the number of rows.
For the uninitiated, a recursive function is a function that calls itself.
Please, provide some insight into the problem.
**
***
****
****
***
**
*
- void inverted(int a)
- {
- if (a==1)
- {
- cout<<"*"<<endl;
- }
- else
- {
- for (int i=0; i<a; i++)
- {
- cout<<"*";
- }
- cout<<endl;
- inverted(a-1);
- }
- }
- void inverted(int a)
- {
- if (a==1)
- {
- cout<<"*"<<endl;
- }
- else
- {
- for (int i=0; i<a; i++)
- {
- cout<<"*";
- }
- cout<<endl;
- inverted(a-1);
- }
- }
Explanation / Answer
for(i=1;iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.